gpt4 book ai didi

javascript - 展平 javascript 对象数组

转载 作者:行者123 更新时间:2023-11-30 07:07:28 25 4
gpt4 key购买 nike

我有一个具有层次结构的对象数组,如下所示:

[
{name: 'ParentOne', children: [
{name: 'ParentOneChildOne'},
{name: 'ParentOneChildTwo', children: [
{name: 'ParentOneChildTwoGrandChildOne'},
]},
]},
{name: 'ParentTwo', children: [
{name: 'ParentTwoChildOne', children: [
{name: 'ParentTwoChildOneGrandChildOne'},
{name: 'ParentTwoChildOneGrandChildTwo'}
]},
{name: 'ParentTwoChildTwo'}
]}
];

我想把它压平:

[
{name: 'ParentOne'},
{name: 'ParentOneChildOne'},
{name: 'ParentOneChildTwo'},
{name: 'ParentOneChildTwoGrandChildOne'},
{name: 'ParentTwo'},
{name: 'ParentTwoChildOne'},
{name: 'ParentTwoChildOneGrandChildOne'},
{name: 'ParentTwoChildOneGrandChildTwo'},
{name: 'ParentTwoChildTwo'}
]

我已经尝试了 _.flatten()_.flatMap(),但它没有产生我需要的结果。最好使用 lodash.jsunderscore.js 实现它的最佳方法是什么。

最佳答案

不需要下划线/lodash。

const arr = [
{name: 'ParentOne', children: [
{name: 'ParentOneChildOne'},
{name: 'ParentOneChildTwo', children: [
{name: 'ParentOneChildTwoGrandChildOne'},
]},
]},
{name: 'ParentTwo', children: [
{name: 'ParentTwoChildOne', children: [
{name: 'ParentTwoChildOneGrandChildOne'},
{name: 'ParentTwoChildOneGrandChildTwo'}
]},
{name: 'ParentTwoChildTwo'}
]}
];

function flatten(arr) {
return arr? arr.reduce((result, item) => [
...result,
{ name: item.name },
...flatten(item.children)
], []) : [];
}

console.log(flatten(arr));

关于javascript - 展平 javascript 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46243349/

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