我有一个这样的 JSON 对象:
var myObject = [
{
"Name" : "app1",
"id" : "1",
"groups" : [
{ "id" : "test1",
"name" : "test group 1",
"desc" : "this is a test group"
},
{ "id" : "test2",
"name" : "test group 2",
"desc" : "this is another test group"
}
]
},
{
"Name" : "app2",
"id" : "2",
"groups" : [
{ "id" : "test3",
"name" : "test group 4",
"desc" : "this is a test group"
},
{ "id" : "test4",
"name" : "test group 4",
"desc" : "this is another test group"
}
]
},
{
"Name" : "app3",
"id" : "3",
"groups" : [
{ "id" : "test5",
"name" : "test group 5",
"desc" : "this is a test group"
},
{ "id" : "test6",
"name" : "test group 6",
"desc" : "this is another test group"
}
]
}
];
我为特定“id”提供了“name”的新值。 如何替换任何对象内特定“id”的“名称”?
以及如何统计所有对象中的组总数?
例如:将名称替换为“test grp45” for id = "test1"
这是 fiddle http://jsfiddle.net/qLTB7/21/
最佳答案
以下函数将搜索一个对象及其所有子对象/数组,并将键替换为新值。它将在全局范围内应用,因此不会在第一次更换后停止。取消注释行以使其成为那样。
function findAndReplace(object, value, replacevalue) {
for (var x in object) {
if (object.hasOwnProperty(x)) {
if (typeof object[x] == 'object') {
findAndReplace(object[x], value, replacevalue);
}
if (object[x] == value) {
object["name"] = replacevalue;
// break; // uncomment to stop after first replacement
}
}
}
}
工作 jsfiddle:http://jsfiddle.net/qLTB7/28/
关于javascript - 数组中的 JSON 对象数组在 javascript 中查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24482814/