Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the property of the difference between two objects in javascript

Let's say that I have an object which looks like this:

{
  prop1: false,
  prop2: false,
  prop3: false
}

and another object which looks like this:

{
  prop1: false,
  prop2: true,
  prop3: false
}

where the difference is within the prop2 property. Is there any way or library (vanilla preferred though) which will compare the two objects, find the property with the different value, and return the property name (in this case prop2)?

I have tried using the difference and differenceBy functions in lodash to no success. Any help or suggestions will be greatly appreciated!

like image 992
milestrong Avatar asked Oct 25 '17 10:10

milestrong


People also ask

How do you find the difference between two objects?

Java equals() Method. The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address.

Can we compare 2 objects in JavaScript?

In JavaScript, we cannot directly compare two objects by equality operators (double equals == or triple equals ===) to see whether they are equal or not. Comparing two objects like this results in false even if they have the same data.


2 Answers

You could filter the keys (assuming same keys) by checking the unequal value.

var obj1 = { prop1: false, prop2: false, prop3: false },
    obj2 = { prop1: false, prop2: true, prop3: false },
    difference = Object.keys(obj1).filter(k => obj1[k] !== obj2[k]);
    
console.log(difference);
like image 65
Nina Scholz Avatar answered Oct 12 '22 13:10

Nina Scholz


This function will extract all the difference between two objects. It will also works on nested objects. This code uses some lodash functions. (function names that starts with "_.")

function difference(object, base) {
    function changes(object, base) {
        return _.transform(object, function(result, value, key) {
            if (!_.isEqual(value, base[key])) {
                result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
            }
        });
    }
    return changes(object, base);
}
like image 30
Zoren Konte Avatar answered Oct 12 '22 13:10

Zoren Konte