vincentsty
vincentsty

Reputation: 3231

Merging two json array object based on union and intersection

I am trying to merge two json array with objects as element. You may refer to this plunkr file for both json. I have succesfully retrieve the expected final outcome array id, but I do not know how to form back the expected json as below. I am using underscore js for this purpose.

Note: If object exist in newJson and not in currentJson, after merge, it will be inactive state by default.

I am not sure whether I am using the correct approach. This is what I have try:

var newJsonID = _.pluck(newJson, 'id');
var currentJsonID =  _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);

Expected Final Outcome:

   [
    {
        "id": "12",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "11",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "10",
        "property1Name": "1"
        "status": "inactive"
    },
    {
        "id": "9",
        "property1Name": "1"
        "status": "active"
    }
]

Upvotes: 0

Views: 2560

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386746

A solution in plain Javascript with two loops and a hash table for lookup.

function update(newArray, currentArray) {
    var hash = Object.create(null);
    currentArray.forEach(function (a) {
        hash[a.id] = a.status;
    });
    newArray.forEach(function (a) {
        a.status = hash[a.id] || 'inactive';
    });
}

var newJson = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
    currentJson = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
   
update(newJson, currentJson);
document.write('<pre>' + JSON.stringify(newJson, 0, 4) + '</pre>');

Upvotes: 2

Related Questions