To compare two JavaScript objects to check if they have the same key-value pairs:

  1. Use JSON.stringify() to convert objects into strings and then compare the JSON strings.
  2. Use Lodash, a 3rd-party library, isEqual() to perform a deep comparison between the objects.

Unlike JavaScript arrays comparison, you can not use === and == operators to perform objects comparison. This is because objects are reference types in JavaScript and only point to the memory location where they are stored.

JSON.stringify() Method

The fastest and simplest way to compare two objects is to convert them to strings by using the JSON.stringify() method and then use the comparison operator to check if both strings are equal:

const obj1 = { burger: '🍔', pizza: '🍕' };
const obj2 = { burger: '🍔', pizza: '🍕' };

// compare objects
if (JSON.stringify(obj1) === JSON.stringify(obj2)) {
    console.log('Objects are equal!');
} else {
    console.log('Objects are not equal.');
}

// Objects are equal!

This method works only when the key-value pairs have the same order. If the key-value pairs are arranged differently in the two objects but are the same, this method will return false:

const obj1 = { burger: '🍔', pizza: '🍕' };
const obj2 = { pizza: '🍕', burger: '🍔' };

// compare objects
if (JSON.stringify(obj1) === JSON.stringify(obj2)) {
    console.log('Objects are equal!');
} else {
    console.log('Objects are not equal.');
}

// Objects are not equal.

For objects having arbitrary key-value pairs order, you should consider using Lodash's isEqual() method.

Lodash isEqual() Method

The isEqual() method from Lodash performs a deep comparison between two objects to determine if they are equivalent. The key-value pairs order doesn't matter for this method. It will return true as long as key-value pairs exist and are the same. You can even use this method to compare arrays, strings, dates, booleans, array buffers, etc.

Here is an example:

const _ = require('lodash');

const obj1 = { burger: '🍔', pizza: '🍕' };
const obj2 = { pizza: '🍕', burger: '🍔' };

if (_.isEqual(obj1, obj2)) {
    console.log('Objects are equal!');
} else {
    console.log('Objects are not equal.');
}

// Objects are equal!

To learn more about JavaScript objects, prototypes, and classes, read this article.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.