When you compare objects with JavaScript’s ==
operator, it compares by identity: it will produce true only if both objects are precisely the same value.
Comparing different objects will return false, even if they have identical properties.
let object1 = {value: 10};
let object2 = {value: 10};
console.log(object1 == object2);
// → false
How to deepCompare objects by contents (identical properties and corresponding value). I have tried:
function deepCompare(a, b) {
if (a === b) return true;
if (typeof a !== "object" || typeof b !== "object" || a == null || b == null) {
return false;
}
let keysA = Object.keys(a);
let keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (let key of keysA) {
if (!keysB.includes(key) || !deepCompare(a[key], b[key])) {
return false;
}
}
return true;
}
let a = { name: "Alice", age: 30 };
let b = { name: "Alice", age: 30 };
console.log(a === b); // false
console.log(deepCompare(a, b)); // true
But it seems to be slow. Is there any optimal way to do this.