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

标签 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"
         }
    ]
}

];

我为特定“id”提供了“name”的新值。 如何替换任何对象内特定“id”的“名称”?

以及如何统计所有对象中的组总数?

例如:将名称替换为“test grp45” for id = "test1"

这是 fiddle 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/

关于javascript - 数组中的 JSON 对象数组在 javascript 中查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24482814/

相关文章:

javascript - 如何修复 React Context 的对象不是函数 - TypeError

arrays - 循环跳过已经完成的值

javascript - JSON获取子值

javascript - 如何将数组从 View 传递到 Controller ?使用 Laravel

javascript - 我收到 WARN : IntentDialog - no intent handler found for null when I fill out a form Node. js Bot 框架

javascript - 使用困惑的查询(HTML 表)从 JSON url 添加数据

javascript - JavaScript 中使用 switch 和 if else 语句的不同输出

javascript - 开关的 React-Native ListView 不更新

javascript - 在 if 语句中检查多个数组元素

c - 在循环链接列表中存储用户输入的名称