DEV Community

Cover image for Compare two objects are same or not in JavaScript.
Abdus Shohid Shakil
Abdus Shohid Shakil

Posted on • Edited on

Compare two objects are same or not in JavaScript.

Object is a hash data-structure in javascript used to store data in format of key-values.
In program sometime we need to compare two objects are equal or not. But wait here is a catch you can't compare two object directly like below code.

let person1 = {
  name: "shakil",
  age: 22,
};
let person2 = {
  name: "shakil",
  age: 22,
};

console.log(person1 == person2); // false
console.log(person1 === person2); // false
Enter fullscreen mode Exit fullscreen mode

Why they return false? Because object compare by references by default instead of internal value. Then how to compare?

There are several way to compare

Way 1: JSON.stringify()
JSON.stringify() method convert any object into string format. After converting into string we can compare them.

const compareObjects = (obj1, obj2) => {
  return (
    JSON.stringify(Object.entries(obj1).sort()) ===
    JSON.stringify(Object.entries(obj2).sort())
  );
};

let person1 = {
  name: "shakil",
  age: 22,
};
let person2 = {
  name: "shakil",
  age: 22,
};

console.log(compareObjects(person1, person2)); // true
Enter fullscreen mode Exit fullscreen mode

Explanation: I created an function that take two arguments and converted each of them into Object.entries which return array of [key, value] array. And sort them then it convert into JSON string and just comparing. Note that this method have some limitations.
Reason of sorting is object keys order are not fixed so if we don't sort them there have a risk to return wrong result.

Way 2: _lodash
Lodash modern JavaScript utility library it have a method named isEqual which performs deep comparison between two values that can be any data types.

import _ from "lodash";

let person1 = {
  name: "shakil",
  age: 22,
};
let person2 = {
  name: "shakil",
  age: 22,
};

console.log(_.isEqual(person1, person2)); // true
Enter fullscreen mode Exit fullscreen mode

Way 3: Custom logic
In this way we can manually check two object by converting them in arrays and sort them. After sorting them we can manually compare each elements in objects. If all element match then they are same (by their properties and values, not by their references) else they are not same. Simple logic

const isObject = (obj) => {
  // confirm that it is an object or not
  return typeof obj === "object" && obj !== null;
};
Enter fullscreen mode Exit fullscreen mode
const compareObjects = (obj1, obj2) => {
  /* Step - 1: */
  if (!isObject(obj1) || !isObject(obj2)) return false;

  /* Step - 2: */
  // converting them into array that contain keys of objects
  const obj1Keys = Object.keys(obj1),
    obj2Keys = Object.keys(obj2);

  /* Step - 3: */
  // if number of keys are not same then we can say they are not same
  if (obj1Keys.length !== obj2Keys.length) return false;

  /* Step - 4: */
  for (const key of obj1Keys) {
     if (obj1[key] !== obj2[key] && !isNaN(obj1[key]) && !isNaN(obj2[key])) {
      return false;
    }
  }
  return true;
};
Enter fullscreen mode Exit fullscreen mode
let person1 = {
  name: "shakil",
  age: 22,
};
let person2 = {
  age: 22,
  name: "shakil",
};

compareObjects(person1, person2); // true
Enter fullscreen mode Exit fullscreen mode

Explanation:

Step 1: First we are checking that are they object. If any of them are not an object then return false, they can't be same.

Step 2: Convert each of the object into array which contain their keys.

Step 3: Now if number of keys in both are not same then they are not same.

Step 4: Traverse through each key and compare its corresponding value. If any of the values are not the same, return false. However, when encountering NaN (Not a Number), remember that NaN === NaN evaluates to false, which is an exception. Therefore, if both values are NaN, consider them equal and continue traversal. After traversing all keys and values, if no inequality is found, return true, indicating that all values are the same.

Why NaN===NaN // false I will discuss in another blog.

Thanks for reading.

Top comments (5)

Collapse
 
ivorobioff profile image
Igor Vorobiov

don't use JSON.stringify, the prop order can be different so it doesn't mean that objects are different.

Collapse
 
developerhub profile image
Abdus Shohid Shakil • Edited

Brother I updated the code now it will return right result.

Collapse
 
efpage profile image
Eckehard

JSON.stringify() ignores properties it cannot translate, so it is a bit risky...

Collapse
 
developerhub profile image
Abdus Shohid Shakil

Yes in some cases JSON.stringify() behave unexpected.

Collapse
 
Sloan, the sloth mascot
Comment deleted