15

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!

milestrong
  • 237
  • 1
  • 3
  • 10

3 Answers3

41

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    This solution does not take in account that the input could be a nested object. A better solution could be the one here https://stackoverflow.com/questions/30476150/javascript-deep-comparison-recursively-objects-and-properties, adding the keys differences as result. – loretoparisi Apr 09 '19 at 10:31
  • 4
    @loretoparisi, this solution takes exactly the object of the op, not a not given nested object. – Nina Scholz Apr 09 '19 at 10:40
  • you are right, I mean to be as generic as possible. – loretoparisi Apr 09 '19 at 10:43
  • @NinaScholz so I have asked new question here https://stackoverflow.com/questions/55591096/compare-nested-objects-in-javascript-and-return-keys-equality – loretoparisi Apr 09 '19 at 10:52
  • [Not work for KeyboardEvent object](https://stackoverflow.com/questions/59235864/object-keyskeyboardevent-only-get-one-istrusted-key-rather-than-all-keys) – illiterate Dec 08 '19 at 13:30
3

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);
}
Zoren Konte
  • 306
  • 4
  • 12
-9

this is the fastest and simplest method

var a ={
  prop1: false,
  prop2: false,
  prop3: false
}

var b={
  prop1: false,
  prop2: true,
  prop3: false
}

 JSON.stringify(a) === JSON.stringify(b) 

this return false. order of props is also important

Rahul
  • 462
  • 1
  • 4
  • 16