【发布时间】:2020-08-01 08:44:38
【问题描述】:
我有一个平面对象数组,我需要一个(深度)嵌套的对象数组。
我的平面数组(ID 在现实中是随机的,但为了清楚起见在这里更改了,嵌套可能很深):
const tags = [
{
id: 'tag1',
title: 'Tag 1',
childIds: ['tag11', 'tag12'],
root: true
},
{
id: 'tag11',
title: 'Tag 11',
childIds: ['tag111', 'tag112'],
},
{
id: 'tag12',
title: 'Tag 12',
childIds: ['tag121']
},
{
id: 'tag111',
title: 'Tag 111',
childIds: []
},
{
id: 'tag112',
title: 'Tag 112',
childIds: []
},
{
id: 'tag121',
title: 'Tag 121',
childIds: []
}
]
我想要的输出:
tagsNested = [
{
id: 'tag1',
title: 'Tag 1',
tags: [
{
id: 'tag11',
title: 'tag 11',
tags: [
{
id: 'tag111',
title: 'Tag 111',
tags: []
},
{
id: 'tag112',
title: 'Tag 112',
tags: []
}
]
},
{
id: 'tag12',
title: 'tag 12',
tags: [
{
id: 'tag121',
title: 'Tag 121',
tags: []
}
]
}
]
}
]
到目前为止,我尽最大努力将所有标签嵌套在任何标签下。
即我确实得到了一个嵌套数组,但每个标签数组都包含所有标签。
function unflatten(tag, nestedTags) {
if (tag.childIds) {
tag.childIds.forEach((childId) => {
var childTag = tags.find((t) => t.id === childId)
childTag.tags = unflatten(childTag, nestedTags)
nestedTags.push(childTag)
})
}
return nestedTags
}
const rootTag = tags.find((tag) => tag.root)
console.log(unflatten(rootTag, []))
我真的很努力地处理这些递归函数,并弄清楚如何让 return 语句为我提供正确的数据。
【问题讨论】:
标签: javascript arrays json recursion data-structures