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>
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.
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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With