将层次结构数组转换为平面数组 [英] Generify transformation of hierarchical array into a flat array

查看:117
本文介绍了将层次结构数组转换为平面数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将分层数组转换为平面数组. 我有这样的对象,它具有相同类型的子代,也具有相同类型的子代,等等.

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.

推荐答案

您可以使用

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

这篇关于将层次结构数组转换为平面数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆