Monday, 12 June 2017

How to create append an array to a json value using(js/node/express)

The quick overview is that using NodeJs(i'm learning), I'm trying to re-create a CRUD app that i did using php/mysql etc, that takes a users form information and stores it in a file called "sample-data.json".

Essentially, with NodeJs a user fills in a form, front-end JS takes that info, passes it along to an api route i set up, and then using FS, writes that info to the sample-data.json file etc.

As for what i've tried, and some code(below), once a users hits submit on the form, this code below takes that info, and passes it to the "sampledataapi" route.

$("#createTodoForm").submit(function(evt){
            evt.preventDefault();

            $.post("/sampledataapi",{
                todoCompany : $("#todoTitle").val(), 
                thisTodoIsFor : $("#todoIsFor").val(),  
                todoPostedBy : $("#todoPostedBy").val(), 
                todoCompleted : $("#todoCompleted").val(), 
                todoPriority : $("#todoPriority").val(), 
                todoMessages : $("#todoFirstMessage").val()
            }, showDataGotten );

        }); 

Once it saves the data, my sample-data.json file which initially has an empty array inside of it, then gets populated with info.

So sample-data.json goes from this: []

To this(once data has been entered):

[
    {
        "todoCompany":"sample company",
        "thisTodoIsFor":"todo is for me",
        "todoPostedBy":"admin",
        "todoCompleted":"no",
        "todoPriority":"green",
        "todoMessages" : "sample message"
    }
]

Now when i do this, all works fine but where i run into problems is that, i want to have "todoMessages" be an array from the get go. Reason being is because once the user posts their data, they will have the ability to erase/add messages from that block.

So what i need is, that when the user submits the data, instead of that "todoMessages" being a regular string, i want it to be like this

"todoMessages" : [ "sample message" ]

This way, i can push info into it OR delete from it etc. How can i make it so that when the user creates his data, and the data passes the info to the route/json file, that it automatically creates todoMessages as an array?

I've been on this for a day or three, and im completely stuck lol. Thanks in advanced for your help everyone.



via somdow

No comments:

Post a Comment