合并具有相同密钥的节点

时间:2018-01-09 21:03:58

标签: javascript arrays typescript

我有一个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)..请告知如何解决这个问题..

1 个答案:

答案 0 :(得分:0)

一种常见且有效的方法是使用公共属性值作为键创建一个hashmap对象,使用完整对象作为值

然后,查看该密钥是否已存在是一个简单的查找。如果是,请将当前值与hashmap中的当前值合并。然后finlly从hashmap中获取合并结果

const tmp ={}

ParentObj.children.forEach((o) => {
  const path = o.data.filePath;
  if (tmp[path]) {
    tmp[path].children = tmp[path].children || [];// in case no children property or array exists
    tmp[path].children.push(...o.children)
  } else {
    tmp[path] = o;
  }
  
});

ParentObj.children = Object.values(tmp);
console.log(ParentObj)
.as-console-wrapper {	max-height: 100%!important;}
<script>
  const 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": "zirconium"
        },
        "children": [{
          "data": {
            "filePath": "srd13_B-103.json"
          },
          "children": []
        }]
      }]
    }]
  }
</script>