EN
JavaScript - deep compare of two objects
9
points
In this article we are going to look how to compare two objects using deep comparions in JavaScript.
By default JavaScript provides ==
and ===
operators. But thay are not enought to compare complex objects, because they compares only references for them. To solve this problem it is necessary to attach external library or write some custom function.
Below simple custom implementation of equals()
method is presented.
Practical example
Presented solution in this section uses recursion to compare properties.
// ONLINE-RUNNER:browser;
function equals(a, b) {
if (a === b) {
return true;
}
if (a instanceof Object && b instanceof Object) {
if (a.constructor !== b.constructor) {
return false;
}
for (const key in a) {
if (a.hasOwnProperty(key)) {
if (!b.hasOwnProperty(key) || !equals(a[key], b[key])) {
return false;
}
}
}
for (const key in b) {
if (b.hasOwnProperty(key) && !a.hasOwnProperty(key)) {
return false;
}
}
return true;
}
return false;
}
// Usage example:
var object1 = {
name: 'John',
items: [1, 2, '3', {name: 'Item'}]
};
var object2 = {
name: 'John',
items: [1, 2, '3', {name: 'Item 2'}]
};
var array1 = [1, 2, 3];
var array2 = [1, 2, '3'];
console.log(equals(1, 1)); // true
console.log(equals('abc', 'abc')); // true
console.log(equals(null, null)); // true
console.log(equals(true, false)); // false
console.log(equals(123, '123')); // false
console.log(equals(object1, object1)); // true
console.log(equals(object1, object2)); // false
console.log(equals(array1, array1)); // true
console.log(equals(array1, array2)); // false