【发布时间】:2018-01-19 05:40:13
【问题描述】:
我有一个可能有相同键的 Treenode..我需要合并它们,这样就没有重复的文件夹..
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": []
}]
}]
}]
}]
我需要合并硼化物,使钛和锆在硼化物之下。 硼化物将成为钛和锆的母体。
结构是
硼化物-
- 钛 - B-102.json
- 锆 - B103.json
这是我的代码..
var arr = JSON.stringify(parentObj);
var result = [];
for (var i = 0; i < arr.length; i++) {
console.log("inside i loop");
var found = false;
for (var j = 0; j < result.length; j++) {
console.log("inside i loop");
if (result[j].children.filePath == arr[i].children.filePath) {
found = true;
result[j].nodes = result[j].nodes.concat(arr[i].nodes);
break;
}
}
if (!found) {
result.push(arr[i]);
}
}
感谢您的帮助
更新:如果我在第二级有相同的钛文件夹,文件夹会重复(更新 JSON)..请告知如何解决这个问题..
【问题讨论】:
-
注意:为什么
JSON.parse(JSON.stringify(parentObj))? -
parentObj 是一个treenode..所以我试图转换成字符串,然后再转换成数组
-
只有顶层可能有重复吗?
-
你指定
ParentObj的方式(首字母大写:代码故障的第一个原因),它已经是一个数组了。 -
现在..只有顶层有重复
标签: javascript arrays typescript