【发布时间】:2019-05-22 02:30:13
【问题描述】:
我有一个对象数组,每个对象都有一个 id 作为键。每个对象代表 id 的导航列表。
我需要将所有导航列表合并到一个大列表中,其中叶子包含所属的 id。
生成的对象应该不包含数组,而是包含将成为 id 列表的叶子。
我已经尝试过递归解决方案,lodash 函数,如合并和分配,但我坚持对象的深度
输入的 JSON 例如:
[
{
"id0": [
{
"Topitem 1": [
{
"Subitem 1": [
"Leaf 1"
]
}, {
"Subitem 2": [
"Leaf 2"
]
}
]
},
{
"Topitem 1": [
{
"Subitem 3": [
"Leaf 1"
]
}
]
},
{
"Topitem 2": [
"Leaf 1",
"Leaf 3"
]
},
{
"Topitem 3": [
{
"Subitem 1": [
{
"SubSubitem 1": [
"Leaf 4"
]
}
]
}
]
}
]
},
{
"id1": [
"Leaf 5"
]
},
{
"id2": [
"Leaf 5"
]
},
{
"id3": [
{
"Topitem 1": [
"Leaf 1",
{
"Subitem 2": [
"Leaf 2",
"Leaf 3"
]
}
]
}, {
"Topitem 2": [
"Leaf 1",
"Leaf 2"
]
}
]
},
{
"id4": [
"Leaf 5"
]
}
]
预期的输出是:
{
"Topitem 1": {
"Subitem 1": {
"Leaf 1": ["id0"]
},
"Subitem 2": {
"Leaf 2": ["id0","id3"],
"Leaf 3": ["id3"]
},
"Subitem 3": {
"Leaf 1": ["id0"]
},
"Leaf 1": ["id3"]
},
"Topitem 2": {
"Leaf 1": ["id0","id3"],
"Leaf 2": ["id0","id3"]
},
"Topitem 3": {
"Subitem 1": {
"SubSubitem 1": {
"Leaf 4": ["id0"]
}
}
},
"Leaf5": ["id1","id2","id4"]
}
【问题讨论】:
标签: javascript arrays json object merge