如何从 JavaScript 中的 JSON 树获取嵌套的父路径?

How to get nested parent path from a JSON tree in JavaScript?

我有一个像这样的 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() 时,它应该 return 我从根开始的点符号字符串路径。在这种情况下,函数的预期 return 字符串将是 "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'));