javascript - Json:编辑深度嵌套的值

标签 javascript json

我有一个像这样的 json 数组:

var tree = [
      {
        text: "Parent 1",
        id: 1,
        nodes: [
          {
            text: "Child 1",
            id: 2,
            nodes: [
              {
                text: "Grandchild 1"
                id: 3,
              },
              {
                text: "Grandchild 2"
                id: 4,
                nodes: [
                  {
                    text: "Grandchild 3"
                    id: 10,
                  },
                  {
                    text: "Grandchild 4"
                    id: 11,
                    nodes: [
                      {
                        text: "Grandchild 5"
                        id: 12,
                      },
                      {
                        text: "Grandchild 6"
                        id: 13,
                      }
                    ]
                  }
                ]
              }
            ]
          },
          {
            text: "Child 2"
            id: 5,
          }
        ]
      },
      {
        text: "Parent 2"
        id: 6,
      },
      {
        text: "Parent 3"
        id: 7,
      },
      {
        text: "Parent 4"
        id: 8,
      },
      {
        text: "Parent 5"
        id: 9,
      }
    ];

我正在尝试创建一个将树、id 和 newText 参数作为参数的函数,它将找到具有给定 id 的节点,用 newText 替换文本,并返回修改后的 json。

例如:

editTree(tree, 11, "Granchild 13435")

有办法实现吗? 我不知道如何解决这个问题,因为我需要 key 的路径才能编辑树。

最佳答案

您可以为此使用递归函数。

var tree = [{"text":"Parent 1","id":1,"nodes":[{"text":"Child 1","id":2,"nodes":[{"text":"Grandchild 1","id":3},{"text":"Grandchild 2","id":4,"nodes":[{"text":"Grandchild 3","id":10},{"text":"Grandchild 4","id":11,"nodes":[{"text":"Grandchild 5","id":12},{"text":"Grandchild 6","id":13}]}]}]},{"text":"Child 2","id":5}]},{"text":"Parent 2","id":6},{"text":"Parent 3","id":7},{"text":"Parent 4","id":8},{"text":"Parent 5","id":9}]

function editTree(tree, id, val) {
  for (var i in tree) {
    if (i == 'id') {
      if (tree[i] == id) {
        tree.text = val
        return 1;
      }
    }
    if (typeof tree[i] == 'object') editTree(tree[i], id, val)
  }
  return tree;
}


console.log(editTree(tree, 11, "Granchild 13435"))

关于javascript - Json:编辑深度嵌套的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42227385/

相关文章:

c# - 如何从 C# 中的 JSON 响应中删除反斜杠?

javascript - 如何使用 forEach 从数组中获取特定值

javascript - 使用 Javascript 淡入淡出文本

javascript - 如何使用 Knockout.js 在数组中绑定(bind)子数组?

javascript - NodeJS 中嵌套的 JSON 对象返回 [Object]

javascript - 访问不常见 JSON 对象中的数据

java - 如何将 JSON 消息从 RabbitMQ 转换为 Java 对象?

javascript - Google Maps API - 外部 JSON 中未显示标记

javascript - 在选择之前检测自动完成建议选项

PHP API 在 POST 中获取空的 JSON 请求