【发布时间】:2021-09-22 22:05:22
【问题描述】:
我希望循环一个对象,该对象也可以具有对象数组,该对象数组可以具有对象数组,依此类推。从理论上讲,这种结构可能是无限的,但这种方式的深度不太可能超过 12 层。
转换前的数据结构示例:
{
id: '1234',
name: 'item 1',
children: [
{
id: '2345',
name: 'item 2',
// other properties that I don't care about will be here too
children: [
{
id: '3456',
name: 'item 3',
children: [
{
id: '4567',
name: 'item 4',
}
],
}
],
}
],
}
我需要最终的数据结构是什么样的(需要一个默认的第一个对象):
const someArray = [
{
// this first child is static and will always be here after transform
title: 'Projects'
key: 'projects',
children: [
{
title: 'item 1', // this is 'name' property
key: '1234,' // this is 'id' property
children: [
{
title: 'item 2',
key: '2345',
children: [
// continue as long as there are children arrays
]
}
]
}
]
}
]
我尝试了几种不同的解决方案,我相信递归函数是解决这个问题的方法,但我只是无法弄清楚如何输出最终结构。我得到了最后两个孩子,但我无法累积以前的孩子。
这是我最接近的非工作解决方案:
const startingObj = [
{
title: 'Projects',
key: 'projects',
}
]
function buildTree (obj) {
// check if we have a children array with at least 1 child.
if (obj?.children?.length) {
return obj?.children.reduce((a, item) => {
if (a) return {
...item.children,
title: a.name || a.title,
key: a.id || a.key,
};
if (item?.children?.length) return buildTree(item.children);
}, obj);
}
}
buildTree(); // would pass in the sample data structure from above here.
我不确定 reduce 是否不是最好的解决方案,或者我只是在我的方法中遗漏了一些关键想法。任何帮助将不胜感激。谢谢。
【问题讨论】:
标签: recursion transformation reduce