数组中的JSON对象数组在javascript中查找和替换 [英] JSON Object array inside array find and replace in javascript

查看:41
本文介绍了数组中的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",我有可用的name"的新值.如何替换任何对象内特定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 ?

例如:将 id = "test1" 的名称替换为 "test grp45"

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 (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/

Working jsfiddle: http://jsfiddle.net/qLTB7/28/

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

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