gpt4 book ai didi

javascript - 合并子树节点中的重复文件路径

转载 作者:行者123 更新时间:2023-11-28 03:45:47 28 4
gpt4 key购买 nike

我正在使用以下 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);

感谢任何帮助。

最佳答案

你需要一些递归来实现这一点。我使用 Array.prototype.reduce() 和递归函数 merge 来合并重复的子节点:

const merge = (data) => {
return data.reduce((result, current) => {
let dup = result.find(d => d.data.filePath === current.data.filePath);
if (!dup) {
result.push(current.children && current.children.length > 0 ? {
data: current.data,
children: merge(current.children)
} : {data: current.data});
} else if (current.children && current.children.length > 0) {
dup.children = merge(dup.children.concat(current.children));
}
return result;
}, []);
};


let 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":[

]
}
]
}
]
}
]
}
];

console.log(JSON.stringify(merge(parentObj), null, ' '));

关于javascript - 合并子树节点中的重复文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483047/

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