lodash - isEqual ignore undefined

Viewed 614

How can I use lodash to deep check the equality of two objects, ignoring undefined.

i.e.

const a = { a: 1, b: 2 };
const b = { a: 1 };

_.isEqual(a, b); // => true
1 Answers

You can use _.isMatch() which performs a partial deep comparison between object (a) and source (b) to determine if object contains equivalent property values to source.

const a = { a: 1, b: 2 };
const b = { a: 1 };

console.log(_.isEqual(a, b)); // false
console.log(_.isMatch(a, b)); // true
console.log(_.isMatch(b, a)); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

This would only work if a key doesn't exist on the source. If a key exist with an explicit value of undefined, the result would be false.

const a = { a: 1, b: 2 };
const b = { a: 1, c: undefined };

console.log(_.isMatch(a, b)); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Related