Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  138] [ 5]  / answers: 1 / hits: 18526  / 6 Years ago, tue, november 20, 2018, 12:00:00

Consider the following deeply nested array:



const array = [
{
id: 1,
name: bla,
children: [
{
id: 23,
name: bla,
children: [{ id: 88, name: bla }, { id: 99, name: bla }]
},
{ id: 43, name: bla },
{
id: 45,
name: bla,
children: [{ id: 43, name: bla }, { id: 46, name: bla }]
}
]
},
{
id: 12,
name: bla,
children: [
{
id: 232,
name: bla,
children: [{ id: 848, name: bla }, { id: 959, name: bla }]
},
{ id: 433, name: bla },
{
id: 445,
name: bla,
children: [
{ id: 443, name: bla },
{
id: 456,
name: bla,
children: [
{
id: 97,
name: bla
},
{
id: 56,
name: bla
}
]
}
]
}
]
},
{
id: 15,
name: bla,
children: [
{
id: 263,
name: bla,
children: [{ id: 868, name: bla }, { id: 979, name: bla }]
},
{ id: 483, name: bla },
{
id: 445,
name: bla,
children: [{ id: 423, name: bla }, { id: 436, name: bla }]
}
]
}
];


How would I grab a certain object by key that might be deeply nested, using recursion?
I have tried this, but this won't work for nesting deeper than 2 levels, it then just returns undefined:



const findItemNested = (arr, itemId, nestingKey) => {
for (const i of arr) {
console.log(i.id);
if (i.id === itemId) {
return i;
}
if (i[nestingKey]) {
findItemNested(i[nestingKey], itemId, nestingKey);
}
}
};


The result should be:



const res = findItemNested(array, 959, children); >> { id: 959, name: bla }



This can perhaps also be achieved using .find, or just to flatten the array (by the children key), but using recursion seems like the most logical solution to me. Does anybody have a solution to this?



Thanks in advance :).


More From » recursion

 Answers
1

You might use a recursive reduce:





const array=[{id:1,name:bla,children:[{id:23,name:bla,children:[{id:88,name:bla},{id:99,name:bla}]},{id:43,name:bla},{id:45,name:bla,children:[{id:43,name:bla},{id:46,name:bla}]}]},{id:12,name:bla,children:[{id:232,name:bla,children:[{id:848,name:bla},{id:959,name:bla}]},{id:433,name:bla},{id:445,name:bla,children:[{id:443,name:bla},{id:456,name:bla,children:[{id:97,name:bla},{id:56,name:bla}]}]}]},{id:15,name:bla,children:[{id:263,name:bla,children:[{id:868,name:bla},{id:979,name:bla}]},{id:483,name:bla},{id:445,name:bla,children:[{id:423,name:bla},{id:436,name:bla}]}]}];

const findItemNested = (arr, itemId, nestingKey) => (
arr.reduce((a, item) => {
if (a) return a;
if (item.id === itemId) return item;
if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
}, null)
);
const res = findItemNested(array, 959, children);
console.log(res);




[#53078] Friday, November 16, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;