0

How to merge two object arrays with no two elements with same key 'id'?

var array1 = [{id:"1", expected:"aaa", actual:"xxx"}, {id:"2", expected:"bbb", actual:"yyy"}];
var array2 = [{id:"1", expected:"kkk", actual:"xxx"}, {id:"4", expected:"ccc", actual:"zzz"}];

And the result array should be,

var array3 = [{id:"1", expected:"kkk", actual:"xxx"}, , {id:"2", expected:"bbb", actual:"yyy"}, {id:"4", expected:"ccc", actual:"zzz"}];

The element with id "1" should be added from array2.

1 Answer 1

1

Try this..... First merge them , then remove duplicate

$.merge(array1, array2);

var existingIDs = [];
array1 = $.grep(array1, function(v) {
    if ($.inArray(v.id, existingIDs) !== -1) {
        return false;
    }
    else {
        existingIDs.push(v.id);
        return true;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.