5

How can I compare these below two JavaScript objects to be equal and true

var obj1 = {
  'a': 'something',
  'b': null
};
var obj2 = {
  'a': 'something',
  'b': ''
}

var isTrue = _.isEqual(obj1, obj2);

alert(isTrue);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
imPK
  • 764
  • 2
  • 7
  • 30
  • Possible duplicate of [How to do a deep comparison between 2 objects with lodash?](https://stackoverflow.com/questions/31683075/how-to-do-a-deep-comparison-between-2-objects-with-lodash) – nircraft Nov 05 '19 at 19:41

2 Answers2

9

You can use _.isEqualWith() and create a custom predicate to handle this case:

var obj1 = {
  'a': 'something',
  'b': null
};
var obj2 = {
  'a': 'something',
  'b': ''
}

var isTrue = _.isEqualWith(obj1, obj2, (a, b) => {
  // if both are null or equal to an empty string then they are equal
  if((_.isNull(a) || a === '') && (_.isNull(b) || b === '')) return true;
});

console.log(isTrue);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

In theory, they are not equals. '' !== null.
What you could do, is change every empty value to be null first, an then compare them.

var obj1 = {
  'a': 'something',
  'b': null
};
var obj2 = {
  'a': 'something',
  'b': ''
}



var isTrue = _.isEqual(mapEmptyValueToNull(obj1), mapEmptyValueToNull(obj2));
console.log(isTrue);

// we change every value of '' to null.
function mapEmptyValueToNull(object) {
  Object.keys(object).forEach((key) => {
    if(object[key] === '') {
      object[key] = null;
    }
  });
  return object;
}
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
Nicolas
  • 8,077
  • 4
  • 21
  • 51