Compare Two Objects Javascript Es6

3 min read Jun 27, 2024
Compare Two Objects Javascript Es6

Comparing Objects in JavaScript ES6

JavaScript ES6 introduced new ways to compare objects, making it easier and more efficient than previous methods. This article will discuss two common techniques for comparing objects:

1. Using the Object.is() method

The Object.is() method offers a strict comparison between two objects. It returns true if both objects refer to the same object in memory, otherwise, it returns false. This method considers NaN equal to NaN and distinguishes between +0 and -0, unlike the === operator.

const obj1 = { name: 'John', age: 30 };
const obj2 = { name: 'John', age: 30 };
const obj3 = obj1;

console.log(Object.is(obj1, obj2)); // false - different objects in memory
console.log(Object.is(obj1, obj3)); // true - same object in memory

2. Implementing a custom comparison function

For a more flexible comparison of object properties, we can implement a custom comparison function. This function iterates through the properties of both objects and checks for equality based on our specific requirements.

function compareObjects(obj1, obj2) {
  // Check if both objects have the same number of properties
  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
  }

  // Iterate through the properties of obj1
  for (const key in obj1) {
    // Check if the property exists in obj2 and if their values are equal
    if (!obj2.hasOwnProperty(key) || obj1[key] !== obj2[key]) {
      return false;
    }
  }

  // All properties are equal
  return true;
}

const obj1 = { name: 'John', age: 30 };
const obj2 = { name: 'John', age: 30 };

console.log(compareObjects(obj1, obj2)); // true - all properties are equal

Conclusion

Both Object.is() and custom comparison functions have their advantages. Object.is() is efficient for checking object identity, while custom functions provide more flexibility for comparing object properties based on specific criteria. Choose the appropriate method based on your specific comparison needs.