Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a deep comparison between 2 objects with lodash?

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...

like image 639
JLavoie Avatar asked Jul 28 '15 17:07

JLavoie


People also ask

How do you compare two values of objects?

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.

How do I compare two arrays in Lodash?

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.

What is _ isEqual?

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.


2 Answers

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.

like image 194
JLavoie Avatar answered Sep 30 '22 08:09

JLavoie


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" ] 
like image 43
Adam Boduch Avatar answered Sep 30 '22 08:09

Adam Boduch