Reputation: 3071
Suppose I have a JSON array like:
[{
"box": "box1",
"parent": [{
"id": "box0"
}],
"child": [{
"id": "box2"
}]
},{
"box": "box2",
"parent": [{
"id": "box1"
}],
"child": [{
"id": "box3"
},{
"id": "box4"
}]
}]
Now assume that I want to change a value parent
id
of box2
then how do I do that.
How can I specifically change a particular value?
Upvotes: 1
Views: 95
Reputation: 2594
You can deserialize this JSON string into a javascript object, modify the property in the object and then serializing the javascript object into a JSON string :
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);
Upvotes: 0
Reputation: 1266
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);
Upvotes: 1