TIL Equality Comparisons for objects
POSTED ON:
TAGS: javascript
[ 1, 2, 3 ] === [ 1, 2, 3 ]; // false
{ a: 42 } === { a: 42 } // false
(x => x * 2) === (x => x * 2) // false
JS does not define === as structural equality for object values.
Instead, === uses identity equality for object values.
The referential equality (using === or Object.is()) determines whether the operands are the same object instance.
Instead, you'll have to use a function to do the comparison.
Shallow Equal
Lighter, faster.
const hero1 = {
name: 'Batman',
realName: 'Bruce Wayne'
};
const hero2 = {
name: 'Batman',
realName: 'Bruce Wayne'
};
const hero3 = {
name: 'Joker'
};
shallowEqual(hero1, hero2); // => true
shallowEqual(hero1, hero3); // => false
Fails with nestled objects.
const hero1 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};
const hero2 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};
shallowEqual(hero1, hero2); // => false
**Deep Equal**
For accurate comparison.
function deepEqual(object1, object2) {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
const val1 = object1[key];
const val2 = object2[key];
const areObjects = isObject(val1) && isObject(val2);
if (
areObjects && !deepEqual(val1, val2) ||
!areObjects && val1 !== val2
) {
return false;
}
}
return true;
}
function isObject(object) {
return object != null && typeof object === 'object';
}
const hero1 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};
const hero2 = {
name: 'Batman',
address: {
city: 'Gotham'
}
};
deepEqual(hero1, hero2); // => true
[reference](https://dmitripavlutin.com/how-to-compare-objects-in-javascript/)
Related TILs
Tagged: javascript