繁体   English   中英

如何修改或更改JSON数组中的特定对象?

[英]How to modify or change a particular object from JSON array?

假设我有一个类似JSON的数组:

[{
    "box": "box1",    
    "parent": [{
        "id": "box0"
    }],
    "child": [{
        "id": "box2"
    }]
},{
    "box": "box2",
    "parent": [{
        "id": "box1"
    }],
    "child": [{
        "id": "box3"
    },{
        "id": "box4"
    }]
}]

现在假设我想更改box2的值parent id ,然后该怎么做。

如何具体更改特定值?

 var arr = [{ 'box': 'box1', 'parent': [{ 'id': 'box0' }], 'child': [{ 'id': 'box2' }] }, { 'box': 'box2', 'parent': [{ 'id': 'box1' }], 'child': [{ 'id': 'box3' }, { 'id': 'box4' }] }]; arr = arr.map(function(box) { if (box.box === 'box2') { box.parent = [{ id: 'box0' }]; } return box; }); console.log(arr); 

您可以将此JSON字符串反序列化为javascript对象,修改对象中的属性,然后将javascript对象序列化为JSON字符串:

var json = '[{"box":"box1","parent":[{"id":"box0"}],"child":[{"id":"box2"}]},{"box":"box2","parent":[{"id":"box1"}],"child":[{"id":"box3"},{"id":"box4"}]}]';
var obj = JSON.parse(json);
obj[1].parent[0].id = "whatever";
var newjson = JSON.stringify(obj);

暂无
暂无

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

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