Skip to content Skip to sidebar Skip to footer

Function Checking For "deep Equality" Of Nested Objects

I am trying to write a function that checks if two objects have the same values. This function requires that I check for the equality of any objects that are stored as values insid

Solution 1:

Here's one possible solution, but I recommend you find your own, really.

function isEqual(var1, var2) { // Break the comparison out into a neat little function
  if (typeof var1 !== "object") {
    return var1===var2;
  } else {
    return deepEqual(var1, var2);
  }
}

function deepEqual(var1, var2) {
   for (i in var1) { 
      if(typeof var2[i] === "undefined") { // Quick check, does the property even exist?
         return false;
      }
      if (!isEqual(var1[i], var2[i])) {
         return false;
      }
   }
   return true;
}

function areObjectsEqual(obj1, obj2) {
   return deepEqual(obj1, obj2) && deepEqual(obj2, obj1); // Two-way checking
}

You not only need to check if everything in obj1 exists in obj2, but also that everything in obj2 exists in obj1. This solution entails doing the comparison both ways, but you could optimize this greatly.

And some test cases

var v1 = { obj0:"jan", obj:{ name:"jan"}, obj2:"ben" }
var v2 = { obj:{ name:"jan"}, obj2:"ben" }

console.log(areObjectsEqual(v1, v2))

v1 = { obj:{ name:"jan"}, obj2:"ben" }
v2 = { obj:{ name:"jan"}, obj2:"ben" }

console.log(areObjectsEqual(v1, v2))

v1 = { obj:{ name:"jan2"}, obj2:"ben" }
v2 = { obj:{ name:"jan"}, obj2:"ben" }

console.log(areObjectsEqual(v1, v2))

v1 = { obj:{ name:"jan"}, obj2:"ben" }
v2 = { obj:{ name:"jan"}, obj2:"ben", obj3:"pig" }

console.log(areObjectsEqual(v1, v2))

Solution 2:

What you probably want is _.isEqual from the lodash or underscore library.

There is also the deepEqual test from the Chai.js assertion library.


Solution 3:

A simple solution would be to JSON stringify the objects and compare their string representations. As @Jan mentions ...

this will only work if the objects are initialized in the exact same way. If the properties are the same but in a different order, it will fail

...this is a bit brittle but may suit your purposes.


Post a Comment for "Function Checking For "deep Equality" Of Nested Objects"