我正在尝试生成将分层数组转换为平面数组的过程。 我有这种对象,它有相同类型的 child ,有相同类型的 child 等。
[{
id: "123",
children: [
{
id: "603",
children: [
{
id: "684",
children: [
...
]
},
{
id: "456",
children: []
}
]
}
]
}]
我找到了一种将其展平的方法,并且我有嵌套级别数的信息。 一层深(有效):
let result = myArray.flat()
.concat(myArray.flatMap(comm => comm.children));
两层深(有效):
let result = myArray.flat()
.concat(myArray.flatMap(comm => comm.children))
.concat(myArray.flatMap(comm => comm.children.flatMap(comm2 => comm2.children)));
但是我如何在函数中生成此代码以处理任何深度?我已经尝试过了,但它不起作用:
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);
}
});
}
};
我很近,但我找不到路。
最佳答案
您可以将 Array#flatMap
与对象平坦的 child 一起使用。
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; }
关于javascript - Generify 将分层数组转换为平面数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60092438/