将层次数组转换为扁平化数组的泛化转换

4

我正在尝试将层次数组转换为扁平数组。

我有这样的对象,它有相同类型的子级,这些子级又有相同类型的子级,以此类推。

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

我离成功很近,但我还没有找到正确的方法。

声明一个函数并递归调用它? - GrafiCode
当然,但我还没有想出来。 - Dotista
类似这样的代码:function flatter(arr) { arr.flat().concat(arr.flatMap(comm => comm.children)); flatter(arr); } )} 但是你必须在每次递归时检查是否还有更多的子元素。 - GrafiCode
2个回答

5
你可以使用具有对象扁平化子元素的 Array#flatMap 方法。

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; }


1
返回已平铺对象中除了 children 属性之外的所有内容。否则,您将在平铺对象中保留子级。 - Nina Scholz

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接