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 inside the original objects. The approach I have developed (see code below) is to first check the equality of non-object values. Then, if these all match, I iterate over the objects again and make a recursive call to the original function, which allows me to compare each nested level of the two objects.
However, this approach only partially works. The nature of the recursive call means I can only check the equality of nested objects at the first key - value pair in the object. I cannot figure out how to check any additional key-value pairs containing nested objects once the first set of nested objects have been compared and the recursive call returns. Here is the function:
var deepEqual = function(val1, val2) {
if (typeof val1 === 'object' && typeof val2 === 'object') {
for (i in val1) {
for (i in val2){
if (typeof val1[i] !== 'object' && typeof val2[i] !== 'object') {
if (val1[i] !== val2[i]) {
return false
}
}
}
}
for (i in val1) {
for (i in val2){
if (typeof val1[i] === 'object' && typeof val2[i] === 'object') {
return deepEqual(val1[i], val2[i])
}
}
}
return true
}
else if (val1 === val2) {
return true
}
else return false
}
My basic problem is that I believe I need a recursive call to check for the deep equality of nested objects, but that I can only do this check once successfully. Has anybody tried to solve a problem like this? I'll provide examples of my results for specific objects if you need more specific. Thanks!
Here's one possible solution, but I recommend you find your own, really.
You not only need to check if everything in
obj1
exists inobj2
, but also that everything inobj2
exists inobj1
. This solution entails doing the comparison both ways, but you could optimize this greatly.And some test cases
A simple solution would be to JSON stringify the objects and compare their string representations. As @Jan mentions ...
...this is a bit brittle but may suit your purposes.
What you probably want is
_.isEqual
from thelodash
orunderscore
library.There is also the
deepEqual
test from theChai.js
assertion library.