4

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"

Eddie
  • 26,593
  • 6
  • 36
  • 58
Sakti Dash
  • 75
  • 1
  • 5
  • please post your effort (code) to achieve this. – Ahmed Ali Jan 13 '20 at 08:57
  • nested parent path? you'll need to explain what *you* mean by that – Jaromanda X Jan 13 '20 at 08:58
  • Objects are not aware of their "parents", since objects don't have a parent. You've to mark the parent as a property in the objects having a "parent". – Teemu Jan 13 '20 at 09:00
  • Are you trying to implement a binary tree? – AZ_ Jan 13 '20 at 09:01
  • Please add the code you've tried. There are many similar questions: [Get parent and grandparent keys from a value inside a deep nested object](https://stackoverflow.com/q/57711141) and [Javascript - Find path to object reference in nested object](https://stackoverflow.com/q/43636000) and [Find a full object path to a given value with JavaScript](https://stackoverflow.com/q/53543303) – adiga Jan 13 '20 at 09:05

1 Answers1

13

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'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392