Answer the question
In order to leave comments, you need to log in
A function that takes an array of objects as input along with its children. How to get such an array with multilevel nesting?
There is an array of objects
const obj = [
{
name: 'hunter',
isExpanded: true,
children: [
{
name: 'rain',
isExpanded: true,
children: [
{name: 'zevs',
isExpanded: false
},
{name: 'jupiter',
isExpanded: false
},
]
},
{
name: 'vortex',
isExpanded: false
},
{
name: 'fray',
isExpanded: false
},
]
},
{
name: 'focus',
isExpanded: false,
children: [
{
name: 'dizik',
isExpanded: false
},
{
name: 'shank',
isExpanded: true,
children:[
{name: 'storm',
isExpanded: false},
]
},
{
name: 'free',
isExpanded: false
},
]
},
{
name: 'devil',
isExpanded: true,
children: [
{
name: 'defavu',
isExpanded: false
},
{
name: 'hope',
isExpanded: true,
children: [
{name: 'rilay',
isExpanded: false},
{name: 'truth',
isExpanded: false}
]
},
{
name: 'miracle',
isExpanded: false
},
]
}
]
Answer the question
In order to leave comments, you need to log in
const flat = arr =>
(arr || []).reduce((acc, { children, ...n }) => {
if (n.isExpanded || !children) {
acc.push(n, ...flat(children));
} else {
acc.push({ ...n, children });
}
return acc;
}, []);
isExpanded: false
one of the ancestors having a level higher than the parent, thenconst flat = arr =>
(arr || []).reduce((acc, { children, ...n }) => {
const flatChildren = flat(children);
if (n.isExpanded || !children) {
acc.push(n, ...flatChildren);
} else {
acc.push({ ...n, children: flatChildren });
}
return acc;
}, []);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question