阵内JSON对象数组查找并在JavaScript替换 [英] JSON Object array inside array find and replace in javascript

查看:139
本文介绍了阵内JSON对象数组查找并在JavaScript替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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/

这篇关于阵内JSON对象数组查找并在JavaScript替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆