How can I find differences in two sets of objects?

advertisements

Given these two objects

var obj1 = [{ number: 23, team: 'Bulls', lastname: 'Jordan'}];
var obj2 = [{ number: 23, team: 'Bulls', lastname: 'Jordan'}, {number: 23, team: 'Cavaliers', lastname: 'James'}];

How can I iterate through both to return the differences, in this case

{number: 23, team: 'Cavaliers', lastname: 'James'}

I have set up something to the effect of

var difference = {};
if (obj2.length > obj1.length) {
    for (var i = 0; i < obj2.length; i++) {
        for (var j in obj2[i]) {
            for (var k in obj1[i]) {
                if (!(obj2[i][j] === obj1[i][k])) {
                    difference.push(obj2[i][j]);
                }
            }
        }
    }
}

I see why this is wrong, I just can't seem to figure out how to simultaneously loop through the first and second object's keys at the same time to compare them to fix it.


If obj2 is the same as obj1 but with additional items pushed, then the set of changes is simply:

obj2.slice(obj1.length);