我需要从嵌套的json对象中查找和更新json对象。考虑原始的json对象。
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": []
}]
从originaldata(JSON)中找到以下findUpdate记录并更新它们的值。
var findUpdate = {
"sc_iden": "332",
"Sc_name": "My Scene",
"sc_type": "New Type",
"sc_status": "Opened",
"sc_priority": "5",
"sc_owner": "Admin",
"children": []
}
基于sc_iden =“332”搜索originaldata并使用jquery或angularjs更新新值(findUpdate)。
答案 0 :(得分:0)
检查控制台输出(仅在示例中Sc_name
已更改):
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>
&#13;
答案 1 :(得分:0)
看看这个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);
}
});
}
};
它会修改原始数据,因此如果您仍然需要,请保留副本。