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

编程入门 行业动态 更新时间:2024-10-14 16:25:33
本文介绍了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 将分层数组转换为平面数组

本文发布于:2023-11-30 03:40:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   平面   Generify

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!