How to compare two objects - JavaScript

Mo Ibra

Mo Ibra

Jan 6, 2023

In this article we will learn how to compare two objects in JavaScript.

It is very common to compare two objects in JavaScript in JavaScript.


Problem

Now we have a problem which is that we want to compare two objects.

Imagine that you have two objects here, and you want to compare them

// object
const object1 = {
    name: "John",
    age: 30,
};

// object
const object2 = {
    name: "John",
    age: 30,
};

How to solve this problem?

There are many ways to compare objects in JavaScript such as:

  • Using isEqual() method
  • Using JSON.stringify().

Compare two objects using isEqual() method

We can use isEqual() method to compare two objects in JavaScript.

Let's see an example

const loadash = require('lodash');

const object1 = {
    name: "John",
    age: 30,
};

const object2 = {
    name: "John",
    age: 30,
};

if (loadash.isEqual(object1, object2)) {
    console.log(true);
} else {
    console.log(false);
}

Output

true

Compare two objects using JSON.stringify() method

We can use JSON.stringify() to compare two objects as well.

Example

// object
const object1 = {
    name: "John",
    age: 30,
};

// object
const object2 = {
    name: "John",
    age: 30,
};

// Compare
if (JSON.stringify(object1) === JSON.stringify(object2)) {
    console.log(true);
} else {
    console.log(false);
}

Output

true

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: