Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
false

Nested 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
false

Through 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
false

Common 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 true

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.