【发布时间】:2018-07-07 01:45:48
【问题描述】:
我正在使用以下 json 来构建树结构.. 如果您注意到,有 2 个具有相同文件路径的子级硼化物和钛,我需要将它们合并,以免创建重复的文件夹。 我的输出文件夹结构将是
SRD 13
- borides
- titanium
- srd13_B-102.json
- srd13_B-103.json
使用以下 json,硼化物和钛得到重复
输入json
parentObj =
[{
"data": {
"resTitle": "-JANAF Thermochemical Tables - SRD 13"
},
"children": [{
"data": {
"filePath": "borides"
},
"children": [{
"data": {
"filePath": "titanium"
},
"children": [{
"data": {
"filePath": "srd13_B-102.json"
},
"children": []
}]
}]
}, {
"data": {
"filePath": "borides"
},
"children": [{
"data": {
"filePath": "titanium"
},
"children": [{
"data": {
"filePath": "srd13_B-103.json"
},
"children": []
}]
}]
}]
}]
输出 json 将是
[{
"data": {
"resTitle": "-JANAF Thermochemical Tables - SRD 13"
},
"children": [{
"data": {
"filePath": "borides"
},
"children": [{
"data": {
"filePath": "titanium"
},
"children": [{
"data": {
"filePath": "srd13_B-102.json"
}
},
{
"data": {
"filePath": "srd13_B-103.json"
}
}
]
}]
}]
}]
我正在使用以下脚本来合并节点,但它只在第一级寻找相同的文件路径,但在这种情况下,第二级也有相同的文件路径..
const tmp ={}
ParentObj.children.forEach((o) => {
const path = o.data.filePath;
if (tmp[path]) {
tmp[path].children = tmp[path].children || [];
tmp[path].children.push(...o.children)
} else {
tmp[path] = o;
}
});
ParentObj.children = Object.values(tmp);
感谢您的帮助。
【问题讨论】:
标签: javascript arrays typescript ecmascript-6