Javascript Object Deeply Equal

Introduction

Given two objects, returns whether or not the two are deeply equivalent.

The structure of the two objects is the same, and so is the structure of each of their corresponding descendants.

Examples:

deepEquals({a:1, b: {c:3}},{a:1, b: {c:3}}); // true
deepEquals({a:1, b: {c:5}},{a:1, b: {c:6}}); // false
var deepEquals = function(apple, orange) {
  if(Object.keys(apple).length !== Object.keys(orange).length) {
    return false;
  }/*w w  w.java 2s  .  c  o m*/
  for(var key in apple) {
    if(typeof apple[key] === 'object' && typeof orange[key] === 'object') {
      return deepEquals(apple[key], orange[key]);
    } else if(apple[key] !== orange[key]) {
      return false;
    }
  }
  return true;
};
console.log(deepEquals({a:1, b: {c:3}},{a:1, b: {c:3}}));
console.log(deepEquals({a:1, b: {c:5}},{a:1, b: {c:6}}));

Another implementation

function deepEqual(item1, item2) {
    function isObject(item) {
        return typeof item === "object" && item !== null;
    }//from   w  w  w. ja v a  2s.  c o m
    
    if (isObject(item1) && isObject(item2)) {
        // check for same number of keys
        if (Object.keys(item1).length !== Object.keys(item2).length) return false;
        // iterate and compare
        for (var prop in item1) {
            if (item1.hasOwnProperty(prop) && item2.hasOwnProperty(prop)) {
                // recursive call for nested objects
                if (!deepEqual(item1[prop], item2[prop])) return false;
            } else if (item1.hasOwnProperty(prop) || item2.hasOwnProperty(prop)) {
                // if only one has the property
                return false;
            }
        }
        return true;
    } else {
        return item1 === item2;
    }
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// true
console.log(deepEqual(obj, {here: 1, object: 2}));
// false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// true



PreviousNext

Related