I have array of objects with the following structure
const arr = [
{
name: "parent",
children: [
{
name: "child1",
children: [
{
name: "granchild1",
children: [],
class: "level-2 leaf",
config: {
name: "granchild1",
value1: false,
value2: false
}
}
],
class: "level-1 leaf",
config: {
name: "child1",
value1: false,
value2: false
}
},
{
name: "child2",
children: [],
class: "level-1 leaf",
config: {
name: "child2",
value1: false,
value2: false
}
}
],
class: "level-0 group",
config: {
name: "parent",
value1: false,
value2: false
}
}
];
I need to convert these array of objects into a flat sttructure with just config
property in it. Can somehelp me how to do this recursively? Help would be much appreciated
Output should look like
const result = [
{
name: "granchild1",
value1: false,
value2: false
},
{
name: "child1",
value1: false,
value2: false
},
{
name: "child2",
value1: false,
value2: false
},
{
name: "parent",
value1: false,
value2: false
}
];
Code that I tried
const recur = (arr) => {
const res = arr.map((item) => {
let val = item.config;
if (item.children.length) return recur(item.children);
return val;
});
return res;
};
console.log(recur(arr));
CodePudding user response:
You can do it recursevly with passing the array reference by every recurse
const arr1 = [
{
name: "parent",
children: [
{
name: "child1",
children: [
{
name: "granchild1",
children: [],
class: "level-2 leaf",
config: {
name: "granchild1",
value1: false,
value2: false
}
}
],
class: "level-1 leaf",
config: {
name: "child1",
value1: false,
value2: false
}
},
{
name: "child2",
children: [],
class: "level-1 leaf",
config: {
name: "child2",
value1: false,
value2: false
}
}
],
class: "level-0 group",
config: {
name: "parent",
value1: false,
value2: false
}
}
];
let collect = (arr, result = []) => {
arr.forEach(prop => {
result.push({...prop.config})
collect(prop.children, result)
})
return result
}
let result = collect(arr1)
console.log(result)
CodePudding user response:
You can do this using destructuring assignment
and a recursive function:
const arr = [ { name: "parent", children: [ { name: "child1", children: [ { name: "granchild1", children: [], class: "level-2 leaf", config: { name: "granchild1", value1: false, value2: false, }, }, ], class: "level-1 leaf", config: { name: "child1", value1: false, value2: false, }, }, { name: "child2", children: [], class: "level-1 leaf", config: { name: "child2", value1: false, value2: false, }, }, ], class: "level-0 group", config: { name: "parent", value1: false, value2: false, }, }, ];
function flatten(arr) {
let ret = []
arr.forEach(({children, config: {name, value1, value2}}) => {
if (children.length) ret.push(...flatten(children));
delete children;
ret.push({name, value1, value2});
});
return ret;
}
console.log(flatten(arr));