How can I get all the values of the property code
in nested arrays of objects? I mean, no matter how many nesting levels.
[
{code: '1', children: [
{code: '11'}, {code: '12'}
]},
{code: '2', children: [
{code: '21'}, {code: '22', children: [{code: '221'}]}
]},
]
Expected result : [1, 11, 12, 2, 21, 22, 221]
CodePudding user response:
flatMap
is your friend for this, and you can combine it with a recursive function, destructuring function parameters with default value, and array rest syntax.
const flatten = arr => arr.flatMap(
({ code, children=[] }) => [code, ...flatten(children)])
const flatten = arr => arr.flatMap(
({ code, children=[] }) => [code, ...flatten(children)])
const arr = [
{ code: '1', children: [{ code: '11' }, { code: '12' }] },
{ code: '2', children: [{ code: '21' }, { code: '22', children: [{ code: '221' }] }],},
]
console.log(flatten(arr))
By the way, what you have there is a well-known data structure named tree
, you should research more about it, and specially the different ways to traverse them: dfs and bfs.
CodePudding user response:
You can easily achieve this result using recursion and flatMap
as:
function getCodes(arr) {
return arr.flatMap((o) => {
const childrenCodes = o.children ? getCodes(o.children) : [];
return [ o.code, ...childrenCodes];
});
}
const arr = [
{ code: '1', children: [{ code: '11' }, { code: '12' }] },
{ code: '2', children: [{ code: '21' }, { code: '22', children: [{ code: '221' }] }],},
];
function getCodes(arr) {
return arr.flatMap((o) => {
const childrenCodes = o.children ? getCodes(o.children) : [];
return [ o.code, ...childrenCodes];
});
}
console.log(getCodes(arr));
CodePudding user response:
A good example for generator function and dfs or bfs
const laziness = [{
code: '1',
children: [{
code: '11'
}, {
code: '12'
}]
},
{
code: '2',
children: [{
code: '21'
}, {
code: '22',
children: [{
code: '221'
}]
}]
},
]
console.log([...bfs(laziness)])
console.log([...dfs(laziness)])
// bfs
function* bfs(items) {
const queue = [...items]
while (queue.length) {
const item = queue.shift()
yield item.code
if (item.children) {
queue.push(...item.children)
}
}
}
// dfs
function* dfs(items) {
for (const item of items) {
yield item.code
if (item.children) {
yield* dfs(item.children)
}
}
}
CodePudding user response:
You can use recursion to make it work:
function getCode (nestedArray, current = []){
nestedArray.forEach((e)=>{
if ('code' in e) current.push(e.code)
const keys = Object.keys(e);
keys.forEach(k => {
if (Array.isArray(e[k]) getCode(e[k], current);
}
return current;
}
getCode([
{code: '1', children: [{code: '11'}, {code: '12'}]},
{code: '2', children: [{code: '21'}, {code: '22', children: [{code: '221'}]}]},
])