gpt4 book ai didi

javascript - 将数组展开为没有父 ID 但具有级别的树

转载 作者:行者123 更新时间:2023-11-29 16:31:21 25 4
gpt4 key购买 nike

我有点被暗示递归的东西困住了。我正在接收数据 来自 API。它看起来像这样:

const input = [
{ id: 'a', level: 0 },
{ id: 'b', level: 1 },
{ id: 'c', level: 1 },
{ id: 'd', level: 2 },
{ id: 'e', level: 1 },
{ id: 'f', level: 0 },
];

我需要类似的东西

const out = [
{ id: 'a', nodes: [
{ id: 'b', nodes: [] },
{ id: 'c', nodes: [
{ id: 'd', nodes: [] },
] },
{ id: 'e', nodes: [] },
] },
{ id: 'f', nodes: [] },
];

您将如何以优雅的方式实现这一点,例如 out = f(input)

我觉得我们可以通过 reduce 做一个递归嵌套方法,但我没能成功 :)

提前致谢!

最佳答案

您可以为具有对象的最新数组/节点属性的关卡使用辅助数组。

const
input = [{ id: 'a', level: 0 }, { id: 'b', level: 1 }, { id: 'c', level: 1 }, { id: 'd', level: 2 }, { id: 'e', level: 1 }, { id: 'f', level: 0 }],
result = [],
levels = [result];

input.forEach(({ id, level }) =>
levels[level].push({ id, nodes: levels[level + 1] = [] })
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将数组展开为没有父 ID 但具有级别的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56581514/

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