I have a nested object and my goal is to get the path until a key-value pair matches in an array.
My current implementation implements this by strings and concatinating the stringts with da dot (".").
However, instead of that I would like to add all the interim results to the array and push to it. But somehow this does not work.
Code with example Data
const data = [
{
parentId: "1111",
name: "Audi",
children : [
{
parentId: "2222",
name: "Benz",
children : [
{
parentId: "3333",
name: "VW",
children : [
]
}
]
}
]
}
]
const pathTo = (array, target) => {
var result;
array.some(({ parentId, name, children = [] }) => {
if (parentId === target) {
return result = JSON.stringify({"parentId" : parentId, "name" : name});
}
var temp = pathTo(children, target)
if (temp) {
return result = JSON.stringify({"parentId" : parentId, "name" : name}) + "." + temp;
}
});
return result;
};
console.log(pathTo(data, "3333"))
Current Result
{"parentId":"1111","name":"Audi"}.{"parentId":"2222","name":"Benz"}.{"parentId":"3333","name":"VW"}
=> The Path concatenated with a string. But I would like :
Expected Result
[ "{"parentId":"1111","name":"Audi"}", "{"parentId":"2222","name":"Benz"}"{"parentId":"3333","name":"VW"}"]
=> an array with all the elements in subsequent order.