如何使用javascript更新JSON对象而不删除旧值

时间:2018-11-02 07:03:01

标签: javascript json

{
    "request_id": "8123",
    "lease_id": "",
    "renewable": false,
    "lease_duration": 4576,
    "data": {
        "mynew": "123",
        "name": "sample"
    },
    "wrap_info": null,
    "warnings": null,
    "auth": null
}

我正在尝试在数据下添加新值,添加新值后,它应该看起来像这样:

{
    "request_id": "8123",
    "lease_id": "",
    "renewable": false,
    "lease_duration": 4576,
    "data": {
        "mynew": "123",
        "name": "sample"
    },
    {
        "mynew": "xyz",
        "name": "newsample"
    },
    "wrap_info": null,
    "warnings": null,
    "auth": null
}

3 个答案:

答案 0 :(得分:3)

您的data属性应为数组类型,以便您可以添加具有相同对象结构的多个对象,例如:

var obj = {
    "request_id": "8123",
    "lease_id": "",
    "renewable": false,
    "lease_duration": 4576,
    "data": [{
      "mynew": "123",
      "name": "sample"
    }, {
      "mynew": "xyz",
      "name": "newsample"
    }],
    "wrap_info": null,
    "warnings": null,
    "auth": null
};

然后,您可以通过将其推送到data数组来轻松添加新对象:

var obj = {
  "request_id": "8123",
  "lease_id": "",
  "renewable": false,
  "lease_duration": 4576,
  "data": [{
    "mynew": "123",
    "name": "sample"
  }],
  "wrap_info": null,
  "warnings": null,
  "auth": null
};
var newData = {
  "mynew": "xyz",
  "name": "newsample"
};
obj.data.push(newData);
console.log(obj);

答案 1 :(得分:1)

尝试将json格式化为

var json = { "request_id": "8123", "lease_id": "", "renewable": false, "lease_duration": 4576, "data": [{ "mynew": "123", "name": "sample" }], "wrap_info": null, "warnings": null, "auth": null }

将数据制成数组,然后您就可以json.data.push(newObject);

答案 2 :(得分:0)

您可以使用Object.assign(target,newsource)将新值添加到目标对象,而不会丢失先前的数据。它只会更新特定值。 例如。

const obj = {name: 'xyz', email: 'abc@yahoo.com'}
const newobj = Object.assign({obj, {email:'xyz@yahoo.com'})
console.log(newobj)
{name: 'xyz', email:'xyz@yahoo.com'}

对于JSON数据,您可以使用JSON.parse将其转换为对象,完成后,只需使用

JSON.stringfy(newobj)