Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare JS objects with values null and empty string

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/[email protected]/lodash.min.js"></script>
like image 796
imPK Avatar asked Nov 05 '19 19:11

imPK


People also ask

Is empty string same as null in JS?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

What is better null or empty string?

So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.


2 Answers

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/[email protected]/lodash.min.js"></script>
like image 53
Ori Drori Avatar answered Oct 13 '22 20:10

Ori Drori


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/[email protected]/lodash.min.js"></script>
like image 2
Nicolas Avatar answered Oct 13 '22 20:10

Nicolas