Reputation: 113
I need to find and update json object from nested json object. Consider the original json object.
var originaldata=[
{
"sc_iden": "331",
"sc_name": "Scene 1",
"sc_type": "",
"sc_status": "Draft",
"sc_owner": "",
"children": [
{
"sc_iden": "332",
"Sc_name": "Scene1.1",
"sc_type": "",
"sc_status": "Draft",
"sc_priority": "3",
"sc_owner": "",
"children": []
}
]
},
{
"sc_iden": "334",
"sc_name": "Scene2",
"sc_type": "",
"sc_status": "Draft",
"sc_priority": "2",
"sc_owner": "",
"children": []
}]
Find the below findUpdate record from originaldata(JSON) and update their values.
var findUpdate = {
"sc_iden": "332",
"Sc_name": "My Scene",
"sc_type": "New Type",
"sc_status": "Opened",
"sc_priority": "5",
"sc_owner": "Admin",
"children": []
}
Based on sc_iden ="332" search the originaldata and update new values(findUpdate) by using jquery or angularjs.
Upvotes: 1
Views: 1855
Reputation: 641
Have a look on this plunker .
var update = function(jsonArray, updatedJson) {
if (jsonArray.length !== 0) {
jsonArray.forEach(function(obj) {
if (obj.sc_iden === updatedJson.sc_iden) {
obj.sc_name = updatedJson.sc_name;
//....update
} else {
//try to update children
update(obj.children, updatedJson);
}
});
}
};
It will modify the original data, so keep a copy if you still need that.
Upvotes: 1
Reputation: 11750
Check the console output (in the example only Sc_name
is changed):
var originaldata=[
{
"sc_iden": "331",
"sc_name": "Scene 1",
"sc_type": "",
"sc_status": "Draft",
"sc_owner": "",
"children": [
{
"sc_iden": "332",
"Sc_name": "Scene1.1",
"sc_type": "",
"sc_status": "Draft",
"sc_priority": "3",
"sc_owner": "",
"children": []
}
]
},
{
"sc_iden": "334",
"sc_name": "Scene2",
"sc_type": "",
"sc_status": "Draft",
"sc_priority": "2",
"sc_owner": "",
"children": []
}];
var findUpdate = {
"sc_iden": "332",
"Sc_name": "My Scene",
"sc_type": "New Type",
"sc_status": "Opened",
"sc_priority": "5",
"sc_owner": "Admin",
"children": []
}
for (i in originaldata) {
var obj = originaldata[i];
if (obj['sc_iden'] == '332') {
obj['Sc_name'] = findUpdate['Sc_name'];
//...
} else {
for (m in obj['children']) {
var k = obj['children'][m];
if (k['sc_iden'] == '332') {
k['Sc_name'] = findUpdate['Sc_name'];
//...
}
}
}
}
console.log(originaldata);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 0