Generify 将分层数组转换为平面数组

Generify transformation of hierarchical array into a flat array

我正在尝试生成将分层数组转换为平面数组的过程。 我有这种object,它有相同类型的children,有相同类型的children等。

[{
        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);
                }
            });
        }
    };

我很近,但找不到路。

const flat = arr => arr.concat(arr.flatMap(it => flat(it.children)));

你可以 Array#flatMap 与 object 持平 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; }