EN
JavaScript - shallow compare of objects
10 points
In this article, we would like to show you how to do shallow compare of objects in JavaScript.
As shallow compare operation we understand properties comparison only on first object level.
Practical example:
xxxxxxxxxx
1
const areEquals = (a, b) => {
2
if (a === b) {
3
return true;
4
}
5
for (const key in a) {
6
if (key in b === false) {
7
return false;
8
}
9
}
10
for (const key in b) {
11
if (key in a === false || a[key] !== b[key]) {
12
return false;
13
}
14
}
15
return true;
16
}
17
18
19
// Usage example:
20
21
const a = {name: 'John'};
22
const b = {name: 'John', age: 25};
23
24
console.log(areEquals(a, a)); // true
25
console.log(areEquals(b, b)); // true
26
27
console.log(areEquals(a, b)); // false
28
console.log(areEquals(b, a)); // false