I have 2 nested objects which are different and I need to know if they have a difference in one of their nested properties.
var a = {}; var b = {}; a.prop1 = 2; a.prop2 = { prop3: 2 }; b.prop1 = 2; b.prop2 = { prop3: 3 };
The object could be much more complex with more nested properties. But this one is a good example. I have the option to use recursive functions or something with lodash...
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.
isEqual() Method. The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.
The _. isEqual() function: is used to find that whether the 2 given arrays are same or not. Two arrays are the same if they have the same number of elements, both the property and the values need to be the same.
An easy and elegant solution is to use _.isEqual
, which performs a deep comparison:
var a = {}; var b = {}; a.prop1 = 2; a.prop2 = { prop3: 2 }; b.prop1 = 2; b.prop2 = { prop3: 3 }; console.log(_.isEqual(a, b)); // returns false if different
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
However, this solution doesn't show which property is different.
If you need to know which properties are different, use reduce():
_.reduce(a, function(result, value, key) { return _.isEqual(value, b[key]) ? result : result.concat(key); }, []); // → [ "prop2" ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With