Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a JSON tree structure like this.

[
    {
      "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"
            }
          ]
        }
      ]
    }
  ]

What i want is when i pass "northeast" to a function() it should return me the dot notation string path from the root. Expected return string from the function in this case would be "links.world.usa.northeast"

like image 587
Sakti Dash Avatar asked Dec 31 '22 09:12

Sakti Dash


1 Answers

You could test each nested array and if found, take the id from every level as path.

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'));
like image 56
Nina Scholz Avatar answered Jan 13 '23 13:01

Nina Scholz