数组中的JSON对象数组在javascript中查找和替换

我有一个像这样的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”提供了“名称”的新值。如何在任何对象内替换特定“ id”的“名称”?

以及如何计算所有对象之间的组总数?

例如:将名称替换为“ test grp45”,ID =“ test1”

这是小提琴 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/

以上是 数组中的JSON对象数组在javascript中查找和替换 的全部内容, 来源链接: utcz.com/qa/427176.html

回到顶部