阵内JSON对象数组查找并在JavaScript替换并在、数组、对象、JSON

2023-09-13 04:41:13 作者:静临烟渚

我有一个JSON对象是这样的:

I have one JSON Object like this :

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的名?

I have new value available of "name" for specific "id". How can I replace "name" of specific "id" inside any object ?

和如何计算组总数的所有对象中?

And how to count total number of groups among all objects ?

例如:更换名称为测试grp45为ID =测试1

for example : replace name to "test grp45" for id = "test1"

下面是小提琴 http://jsfiddle.net/qLTB7/21/

推荐答案

下面的函数将通过目标搜索及其所有子对象/数组,并替换为新价值的关键。这将在全球范围适用,所以先更换后它不会停止。取消对注释行,以这种方式。

The following function will search through an object and all of its child objects/arrays, and replace the key with the new value. It will apply globally, so it won't stop after the first replacement. Uncomment the commented line to make it that way.

function findAndReplace(object, value, replacevalue){
  for(var x in object){
    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/