本文介绍了Generify 将分层数组转换为平面数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将分层数组的转换泛化为平面数组.我有这种对象,它有相同类型的孩子,有相同类型的孩子等等.
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));两层深度(有效):
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.
推荐答案你可以使用 Array#flatMap 带有平面子对象.
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; }更多推荐
Generify 将分层数组转换为平面数组
发布评论