Languages
[Edit]
EN

JavaScript - deep compare of two objects

9 points
Created by:
FryerTuck
649

In this article we are going to look how to compare two objects using deep comparions in JavaScript.

By default JavaScript provides == and === operators. But thay are not enought to compare complex objects, because they compares only references for them. To solve this problem it is necessary to attach external library or write some custom function.

Below simple custom implementation of equals() method is presented.

Practical example

Presented solution in this section uses recursion to compare properties.

// ONLINE-RUNNER:browser;

function equals(a, b) {
    if (a === b) {
        return true;
    }
    if (a instanceof Object && b instanceof Object) {
        if (a.constructor !== b.constructor) {
          return false;
        }
        for (const key in a) {
            if (a.hasOwnProperty(key)) {
                if (!b.hasOwnProperty(key) || !equals(a[key], b[key])) {
                    return false;
                }
            }
        }
        for (const key in b) {
            if (b.hasOwnProperty(key) && !a.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }
    return false;
}



// Usage example:

var object1 = {
	name: 'John',
  	items: [1, 2, '3', {name: 'Item'}]
};

var object2 = {
	name: 'John',
  	items: [1, 2, '3', {name: 'Item 2'}]
};

var array1 = [1, 2, 3];
var array2 = [1, 2, '3'];

console.log(equals(1, 1));              // true
console.log(equals('abc', 'abc'));      // true
   
console.log(equals(null, null));        // true
console.log(equals(true, false));       // false
console.log(equals(123, '123'));        // false

console.log(equals(object1, object1));  // true
console.log(equals(object1, object2));  // false
console.log(equals(array1, array1));    // true
console.log(equals(array1, array2));    // false

 

See also

  1. JavaScript - deep compare of two objects with differences printing

Alternative titles

  1. Java equals method equivalent in javascript
  2. How to compare two complex objects in javascript?
  3. JavaScript - deep object comparison
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join