0

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!

0

3 Answers 3

3

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 );

Sign up to request clarification or add additional context in comments.

2 Comments

The original question asked for JSON (which is a string) to be modified. This answer modifies an object.
@MartinJoiner well, if need be, OP can get the object back to JSON with JSON.stringify( obj );
1

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

1 Comment

This answers the question better as it specifically asked for JSON to be modified but the accepted answer modifies a JavaScript object.
0
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 !

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.