javascript - 如何在 JavaScript 中从 JSON 树获取嵌套父路径?

标签 javascript json treeview parent-child

我有一个像这样的 JSON 树结构。

[
    {
      "title":"News",
      "id":"news"
    },
    {
      "title":"Links",
      "id":"links",
      "children":[
        {
          "title":"World",
          "id":"world",
          "children":[
            {
              "title":"USA",
              "id":"usa",
              "children":[
                {
                  "title":"Northeast",
                  "id":"northeast"
                },
                {
                  "title":"Midwest",
                  "id":"midwest"
                }                
              ]
            },
            {
              "title":"Europe",
              "id":"europe"
            }
          ]
        }
      ]
    }
  ]

我想要的是,当我将“northeast”传递给 function() 时,它应该返回我从根开始的点符号字符串路径。在这种情况下,函数的预期返回字符串将为“links.world.usa.northeast”

最佳答案

您可以测试每个嵌套数组,如果找到,则将每个级别的 id 作为路径。

const pathTo = (array, target) => {
    var result;
    array.some(({ id, children = [] }) => {
        if (id === target) return result = id;
        var temp = pathTo(children, target)
        if (temp) return result = id + '.' + temp;
    });
    return result;
};

var data = [{ title: "News", id: "news" }, { title: "Links", id: "links", children: [{ title: "World", id: "world", children: [{ title: "USA", id: "usa", children: [{ title: "Northeast", id: "northeast" }, { title: "Midwest", id: "midwest" }] }, { title: "Europe", id: "europe" }] }] }];

console.log(pathTo(data, 'northeast'));

关于javascript - 如何在 JavaScript 中从 JSON 树获取嵌套父路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713227/

相关文章:

javascript - 如何使用 Javascript 读取 JSON 数组以获取值(如果存在)

android - 在android中转换为json数组时android联系人中的问题

java - 来自 JSON 文件的 Java 中的键值对

.net - 如何右键单击以选择 TreeView 控件中的节点

javascript - 在 JavaScript 中提升变量

javascript - 如何使用多个参数过滤对象数组

javascript - CoffeeScript 替换

tkinter - 从 tkinter 中的 TreeView 获取数据

多列中的 QTreeView/QAbstractItemModel 子树

javascript - 更新 URL 而不刷新页面