简体   繁体   English

将数据添加到JSON数组

[英]Adding data to JSON array

I have a JSON Array inside my Node.js code with the following schema: 我的Node.js代码中有一个JSON数组,具有以下架构:

{
    "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. 访问obj变量的data属性以及该数组中的第一个元素,然后在该对象上设置一个与您的字符串相等的新属性。

 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. 由于您已经有了JSON,因此您应该首先对其进行解析,因为JSON是一个字符串。 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. 然后,您必须再次将其转换为JSON字符串。 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 ! 希望对您有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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