gpt4 book ai didi

javascript - 如何将具有父子关系的嵌套数组转换为普通数组?

转载 作者:行者123 更新时间:2023-12-04 00:51:01 24 4
gpt4 key购买 nike

我有一个嵌套对象的数组,它们具有如下父子关系:

[
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4, children: []},
{id: 6, title: 'hello', parent: 4, children: []}
]},
{id: 7, title: 'hello', parent: 3, children: []}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2, children: []}
]}
]
我需要将其转换为保留父子关系的普通数组,并且按照父子的顺序及其所有子节点首先返回,然后再继续下一个父节点。
[
{id: 1, title: 'hello', parent: 0},
{id: 3, title: 'hello', parent: 1},
{id: 4, title: 'hello', parent: 3},
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4},
{id: 7, title: 'hello', parent: 3},
{id: 2, title: 'hello', parent: 0},
{id: 8, title: 'hello', parent: 2}
]
我能够使用递归函数进行相反的转换。
但我需要以一种有效的方式做相反的事情。如示例嵌套数组所示,存在多级嵌套。
编辑:将嵌套数组更新为叶节点有一个空的子数组。
而且,ES5 中的答案会有所帮助。

最佳答案

我只是使用一个简单的递归函数将一个数组对象变成一个普通数组

var arr = [ {id: 1, title: 'hello', parent: 0, children: [ {id: 3, title: 'hello', parent: 1, children: [ {id: 4, title: 'hello', parent: 3, children: [ {id: 5, title: 'hello', parent: 4, children: []}, {id: 6, title: 'hello', parent: 4, children: []} ]}, {id: 7, title: 'hello', parent: 3, children: []} ]} ]}, {id: 2, title: 'hello', parent: 0, children: [ {id: 8, title: 'hello', parent: 2, children: []} ]} ];

var result = [];
var convertArrToObj = (arr) => {
arr.forEach(e => {
if (e.children) {
result.push({
id: e.id,
title: e.title,
parent: e.parent
});
convertArrToObj(e.children);
} else result.push(e);

});
};
convertArrToObj(arr);
console.log(result);

关于javascript - 如何将具有父子关系的嵌套数组转换为普通数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66651478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com