sur*_*erd 7 javascript arrays json angularjs
我有一个像这样的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"
}
]
}
];
Run Code Online (Sandbox Code Playgroud)
我为特定的"id"提供了"name"的新值.如何在任何对象中替换特定"id"的"名称"?
以及如何计算所有对象中的组总数?
例如:为id ="test1"将名称替换为"test grp45"
Pit*_*taJ 15
以下函数将搜索对象及其所有子对象/数组,并使用新值替换该键.它将全球适用,因此在第一次更换后不会停止.取消注释注释行以使其成为那样.
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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
工作jsfiddle:http://jsfiddle.net/qLTB7/28/
| 归档时间: |
|
| 查看次数: |
33009 次 |
| 最近记录: |