Answer the question
In order to leave comments, you need to log in
How to expand nested array?
There is an object that stores data in which there are nested child arrays. I want all nested child arrays to lie at the same level in the new array.
Any ideas how to do this - only recursive deployment comes to mind?
Answer the question
In order to leave comments, you need to log in
Only recursively.
const nested = {
id: 1,
children: [
{ id: 2 },
{ id: 3,
children: [{ id: 5 }, { id: 6 }]
},
{ id: 4 }
]
}
const flatten = function(obj) {
const array = Array.isArray(obj) ? obj : [obj];
return array.reduce(function(acc, value) {
acc.push(value);
if (value.children) {
acc = acc.concat(flatten(value.children));
delete value.children;
}
return acc;
}, []);
}
flatten(nested); // => [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 6 }, { id: 4 } ]
If I understand correctly, you need to make a flat array.
look at the implementation of flatten and flattenDeep in lodash
or here ready: MDN
I don't know how efficient it is, but it will expand any nesting
for an array of strings or numbers, which will become strings in the final array
arr.toString().split(',')
arr.join().split(',')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question