Storing data in a variable is very common, and this time we have it as follows:
let categories = [
{
name: "a",
nodes: [
{
name: "aa",
nodes: [
{
name: "aaa"
}
]
},
{
name: "ab",
},
{
name: "ac",
},
{
name: "ad",
}
]
},
{
name: "b",
nodes: [
{
name: "ba",
},
{
name: "bb",
},
{
name: "bc",
},
{
name: "bd",
}
]
}
];
We also have a recursive function designed to work with the variables mentioned above - categories and name.
function getCategoryParents(categories, name) {
for (let index = 0; index < categories.length; index++) {
const category = categories[index];
if (category.name === name) {
}
if (category.nodes && category.nodes.length) {
category.nodes.forEach(cat => this.getCategoryParents([cat], name));
}
}
}
The goal here is to generate an array of names that includes the provided name along with its parent names.
For instance, calling
getCategoryParents(categories, "aaa")
should result in ["a", "aa", "aaa"]. This is because aa is the parent of aaa and a is the parent of aa.
I hope this explanation serves its purpose.