Last month, we looked at various ways to compare two arrays in JavaScript to find if they are equal. Today, you'll learn how to compare two JavaScript objects to check if they have the same key-value pairs.

Unfortunately, just like arrays, you can not use === and == operators to perform objects comparison. This is because objects are reference types in JavaScript, and they 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 that have arbitrary key-value pairs order, you should consider using Lodash's isEqual() method.

Lodash's isEqual() Method

Lodash's isEqual() method 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, and more.

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, take a look at this article.

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

Last Updated: