How to compare two objects
Short answer
For flat objects, compare the number of keys and the value of each key:
const shallowEqual = (a, b) => {
const keys = Object.keys(a);
return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);
};
console.log(shallowEqual({ x: 1, y: 2 }, { y: 2, x: 1 }));
console.log(shallowEqual({ x: 1 }, { x: 2 }));Output:
true
falseNested objects
A recursive function goes into nested objects and arrays:
const deepEqual = (a, b) => {
if (a === b) return true;
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
const keys = Object.keys(a);
return keys.length === Object.keys(b).length && keys.every((key) => deepEqual(a[key], b[key]));
};
console.log(deepEqual({ user: { tags: ['a', 'b'] } }, { user: { tags: ['a', 'b'] } }));
console.log(deepEqual({ user: { tags: ['a'] } }, { user: { tags: ['b'] } }));Output:
true
falseThrough JSON
Comparing JSON strings is short, but it depends on the order of keys:
console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ a: 1, b: 2 }));
console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 }));Output:
true
falseCommon mistake
=== and == compare objects by reference: they are equal only if both variables point to the same object:
const a = { x: 1 };
const b = { x: 1 };
const c = a;
console.log(a === b, a === c);Output:
false trueFunctions used in this recipe
- Object.keys — Returns an array of an object's property names.
- JSON.stringify — Converts a value to a JSON string.