问题
I'm trying to generify the transformation of a hierarchical array into a flat array. I have this kind of object which has children of the same type, which has children of the same type etc..
[{
id: "123",
children: [
{
id: "603",
children: [
{
id: "684",
children: [
...
]
},
{
id: "456",
children: []
}
]
}
]
}]
I found a way to flatten it and I have the information of the number of nested levels. One level deep (works):
let result = myArray.flat()
.concat(myArray.flatMap(comm => comm.children));
Two levels deep (works):
let result = myArray.flat()
.concat(myArray.flatMap(comm => comm.children))
.concat(myArray.flatMap(comm => comm.children.flatMap(comm2 => comm2.children)));
But how can I generify this code in a function to handle any deepness ? I already tried this but it does not work:
flatFunct = (myArray, deep) => {
let func = comm => comm.children;
let flatMapResult = myArray.flat();
for (let i = 0; i < deep; i++) {
flatMapResult = flatMapResult.concat(() => {
let result = myArray;
for (let j = 0; j < i; j++) {
result = result.flatMap(func);
}
});
}
};
I'm close, but I don't find the way.
回答1:
You could take Array#flatMap with object flat children.
const
flat = ({ children = [], ...o }) => [o, ...children.flatMap(flat)],
data = [{ id: "123", children: [{ id: "603", children: [{ id: "684", children: [{ id: "688", children: [] }] }, { id: "456", children: [] }] }] }],
result = data.flatMap(flat);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
回答2:
const flat = arr => arr.concat(arr.flatMap(it => flat(it.children)));
来源:https://stackoverflow.com/questions/60092438/generify-transformation-of-hierarchical-array-into-a-flat-array