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

JLavoie picture JLavoie · Jul 28, 2015 · Viewed 338.9k times · Source

I have 2 nested objects which are different and I need to know if they have 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...

Answer

JLavoie picture JLavoie · Jul 28, 2015

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.