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.
Presented solution in this section uses recursion to compare properties.
xxxxxxxxxx
1
function equals(a, b) {
2
if (a === b) {
3
return true;
4
}
5
if (a instanceof Object && b instanceof Object) {
6
if (a.constructor !== b.constructor) {
7
return false;
8
}
9
for (const key in a) {
10
if (a.hasOwnProperty(key)) {
11
if (!b.hasOwnProperty(key) || !equals(a[key], b[key])) {
12
return false;
13
}
14
}
15
}
16
for (const key in b) {
17
if (b.hasOwnProperty(key) && !a.hasOwnProperty(key)) {
18
return false;
19
}
20
}
21
return true;
22
}
23
return false;
24
}
25
26
27
28
// Usage example:
29
30
var object1 = {
31
name: 'John',
32
items: [1, 2, '3', {name: 'Item'}]
33
};
34
35
var object2 = {
36
name: 'John',
37
items: [1, 2, '3', {name: 'Item 2'}]
38
};
39
40
var array1 = [1, 2, 3];
41
var array2 = [1, 2, '3'];
42
43
console.log(equals(1, 1)); // true
44
console.log(equals('abc', 'abc')); // true
45
46
console.log(equals(null, null)); // true
47
console.log(equals(true, false)); // false
48
console.log(equals(123, '123')); // false
49
50
console.log(equals(object1, object1)); // true
51
console.log(equals(object1, object2)); // false
52
console.log(equals(array1, array1)); // true
53
console.log(equals(array1, array2)); // false