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.8k6 gold badges39 silver badges59 bronze badges
asked Jan 13, 2020 at 8:54
5

1 Answer 1

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'));

answered Jan 13, 2020 at 9:19
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.