Generify transformation of hierarchical array into a flat array

自古美人都是妖i 提交于 2020-02-24 10:22:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!