Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates and merge JSON objects

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"
        },
    ]
}]

Regards.

Shreerang

like image 419
Shreerang Avatar asked Oct 24 '25 09:10

Shreerang


1 Answers

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]);
  }
}

Then you can create JSON from the array if that is the end result that you need:

json = JSON.stringify(result);
like image 139
Guffa Avatar answered Oct 26 '25 22:10

Guffa