You probably think comparing two objects in JavaScript is easy. Well, it’s easy for the primitive types, not for the objects.

Keep reading to see how hard it is and how you can take advantage of it to improve your coding skills.

1. Reference Identity

Let’s say you just want to compare object references regardless of their content, then you can use the strict equality (‘===’) or the loose one (‘==’).

For example:

let book1 = {
  title: ‘JavaScript’
};

let book2 = {
  title: ‘JavaScript’
};
let book3 = {
  title: ‘Kotlin’
};
let book4 = book1;
let book5 = book1;
console.log(book1 === book2); // false
console.log(book3 === book2); // false
console.log(book4 === book5); // true

As you can see, the result book1 === book2 is false despite the equality of their content because they have different references.

The same for book3 === book2.

And since book4 and book5 all point to the same object instance, book1, so book 4 === book5 is true.

We rarely compare the object references in real projects. Most of the time, we want to compare the actual values inside the objects.

2. Using JSON.stringify

First, we convert the JavaScript objects to JSON strings and then compare those strings.

For example:

let person1 = {
  name: ‘Amy’,
  age: 28
};
let person2 = {
  name: ‘Amy’,
  age: 28
};
let person3 = {
  name: ‘David’,
  age: 28
};
console.log(JSON.stringify(person1) === JSON.stringify(person2)); // true
console.log(JSON.stringify(person3) === JSON.stringify(person1)); // false
console.log(JSON.stringify(person3) === JSON.stringify(person2)); // false

In the example above, person1 and person2 have the same properties and values, so JSON.stringify(person1) === JSON.stringify(person2) is true.

For** person3**, the property name has the different value from **person1 **and person2. As the result, JSON.stringify(person3) === JSON.stringify(person1) is false and JSON.stringify(person3) === JSON.stringify(person2) is false.

However, using JSON.stringify() to compare objects has one limitation. If the properties of each object do not come in the same order, it doesn’t work.

For example:

let person1 = {
  age: 28,
  name: ‘Amy’
};
let person2 = {
  name: ‘Amy’,
  age: 28
};
console.log(JSON.stringify(person1) === JSON.stringify(person2)); // false

person1 and **person2 **have the same properties with the same values. The only difference is in person1, the property **age **appears before name, meanwhile, in person2, **name **comes before age. In this case, the result of the comparison is false.

3. Using Lodash

To make the comparison thing to be a piece of cake, just leverage Lodash.

Let’s take the above example in which JSON.stringify is useless and hand it over to Lodash:

let person1 = {
  age: 28,
  name: ‘Amy’
};
let person2 = {
  name: ‘Amy’,
  age: 28
};
console.log(_.isEqual(person1, person2)); // true

#javascript #javascript tips #programming #development

4 Ways to Compare Objects in JavaScript
32.25 GEEK