删除重复项并合并JSON对象 [英] Remove duplicates and merge JSON objects
本文介绍了删除重复项并合并JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JSON对象.我需要删除重复项并使用纯Javascript合并内部对象.我该怎么做呢?
I have the following JSON object. I need to remove the duplicates and merge the inner object using plain Javascript. How do I go about doing this?
[{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 20,
"nodeName" : "test1"
}
]
},
{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 21,
"nodeName" : "test2"
}
]
}]
以下是我期望作为输出的对象.
Following is the object that I expect as output.
[{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 20,
"nodeName" : "test1"
},
{
"nodeId" : 21,
"nodeName" : "test2"
},
]
}]
致谢.
Shreerang
Shreerang
推荐答案
首先将JSON转换为Javascript数组,以便您可以轻松访问它:
First turn the JSON into a Javascript array so that you can easily access it:
var arr = JSON.parse(json);
然后为结果创建一个数组,并遍历所有项目,然后与您放入结果中的项目进行比较:
Then make an array for the result and loop through the items and compare against the items that you put in the result:
var result = [];
for (var i = 0; i < arr.length; i++) {
var found = false;
for (var j = 0; j < result.length; j++) {
if (result[j].id == arr[i].id && result[j].name == arr[i].name) {
found = true;
result[j].nodes = result[j].nodes.concat(arr[i].nodes);
break;
}
}
if (!found) {
result.push(arr[i]);
}
}
然后,如果需要的最终结果是,您可以从数组创建JSON:
Then you can create JSON from the array if that is the end result that you need:
json = JSON.stringify(result);
这篇关于删除重复项并合并JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文