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
-
please post your effort (code) to achieve this.Ahmed Ali– Ahmed Ali2020年01月13日 08:57:12 +00:00Commented Jan 13, 2020 at 8:57
-
nested parent path? you'll need to explain what you mean by thatJaromanda X– Jaromanda X2020年01月13日 08:58:16 +00:00Commented Jan 13, 2020 at 8: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– Teemu2020年01月13日 09:00:26 +00:00Commented Jan 13, 2020 at 9:00
-
Are you trying to implement a binary tree?arizafar– arizafar2020年01月13日 09:01:22 +00:00Commented Jan 13, 2020 at 9: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 and Javascript - Find path to object reference in nested object and Find a full object path to a given value with JavaScriptadiga– adiga2020年01月13日 09:05:49 +00:00Commented Jan 13, 2020 at 9:05
1 Answer 1
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
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-js