How to compare two objects in JavaScript

Have you ever wondered how to compare two object in JavaScript? It not much easy as you think and not hard as you imagine.

The object in javascript are reference type and because of that, you can’t check whether they are equal by using === or == signs. Because it always return false for two separate objects.

There are mainly two ways to check, using JSON.stringify() and use the isEqual function provide by the Lodash

Compare two objects using JSON.stringify()

    
const obj1 = { letter: 'A' };
const obj2 = { letter: 'A' };

JSON.stringify(obj1) === JSON.stringify(obj2)
    

The main thing you need to remember when using JSON.stringify() is that the order has to be same in the two object

Compare deep nested object using JSON.stringify()

you can use JSON.stringify() method to check deep nested object also

    
const obj1 = { letter: 'A',vowels:{ first:'A',second:'E',third:'I',fourth:'O',fifth:'U'  } };
const obj2 = { letter: 'A',vowels:{ first:'A',second:'E',third:'I',fourth:'O',fifth:'U'  }};

JSON.stringify(obj1) === JSON.stringify(obj2)
    

Deep comparison between 2 objects with lodash

If the element order of the object is not similar JSON.stringify() will not work. But you can use _.isEqual() method in Lodash library.

    
const obj1 = { vowels:{ first:'A',second:'E',third:'I',fourth:'O',fifth:'U'  },letter: 'A' };
const obj2 = { letter: 'A',vowels:{ first:'A',second:'E',third:'I',fourth:'O',fifth:'U'  }};

_.isEqual(obj1,obj2);
    

Which one is better?

you can use either _.isEqual() or JSON.stringify() based on the usecase. If the order of the keys in the object get change it recommended to use _.isEqual() method. If you are sure about the order and need to do it in quick way without a library JSON.stringify() will works for you.

You Will Like Also