How can I pare 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="/[email protected]/lodash.min.js"></script>
How can I pare 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/npm/[email protected]/lodash.min.js"></script>
Share
Improve this question
edited Nov 5, 2019 at 19:44
Ori Drori
193k32 gold badges238 silver badges229 bronze badges
asked Nov 5, 2019 at 19:38
imPKimPK
8842 gold badges9 silver badges34 bronze badges
1
- Possible duplicate of How to do a deep parison between 2 objects with lodash? – nircraft Commented Nov 5, 2019 at 19:41
2 Answers
Reset to default 9You 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/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 pare 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/npm/[email protected]/lodash.min.js"></script>