简体   繁体   中英

Adding data to JSON array

I have a JSON Array inside my Node.js code with the following schema:

{
    "status": "ok",
    "data": [
        {
            "id": 1,
            "active": true,
            "createdAt": "2017-07-21T15:39:31.000Z",
            "updatedAt": "2017-07-21T15:47:13.000Z"
        }
     ]
 }

and I want to add data so it will look like:

{
    "status": "ok",
    "data": [
        {
            "id": 1,
            "active": true,
            "createdAt": "2017-07-21T15:39:31.000Z",
            "updatedAt": "2017-07-21T15:47:13.000Z",
            "information": "someInformation"
        }
     ]
 }

Can you help me how to do this?

Thanks!

Like this? access the data property, of the obj variable, and the first element in that array, then set a new property on that object equal to your string.

 var obj = { "status": "ok", "data": [ { "id": 1, "active": true, "createdAt": "2017-07-21T15:39:31.000Z", "updatedAt": "2017-07-21T15:47:13.000Z" } ] }; obj.data[0].information = "someInformation"; console.log( obj ); 

Since you have already the JSON you should firstly parse it, because JSON is a string. After parsing you will get object that should be saved in some variable, then you can access it as general object and add the property you want. Then you have to transform it to JSON string again. It will be like this

 var parsed = JSON.parse(data); // Now we are transforming JSON string into the object //Now you may do whatever you want parsed.newprop = 'some text'; parsed.hello = 'Hellow world'; data = JSON.stringify(parsed); // Now we are replacing the previous version of JSON string to new version with additional properties 

var dataContainer = {
     "status": "ok",
     "data": [
      {
        "id": 1,
        "active": true,
        "createdAt": "2017-07-21T15:39:31.000Z",
        "updatedAt": "2017-07-21T15:47:13.000Z"
      }
   ]
};


for(var i = 0; i < dataContainer.data.length; i++) {
  dataContainer['data'][i]['information'] = "some information";
}

Hope it helps you !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM