In Ruby, this was easy- Ruby understood that you wanted to compare the entries that were in a hash:
false instead of
true. Dang it!
However, we have a problem, what happens if one of the values in our object is an object itself? In the below example the
cats key has a value of
 instead of
false for the whole comparison because these two array objects are not the same spot in the computer’s memory.
What do we do now? Recursion. All we need to do is insert a conditional that checks whether the current value is an object itself. If it is, we can feed the current value and its counterpart in the comparison object back into our original
objectsEqual function (line 6 below). This will give us a deep equality check.
Great! All done right? Maybe. The last thing you should ask yourself is whether the order of insertion matters in your object comparison. For example,
b below have the same key/value pairs, but they are in different order. Our current function would say that these two are the same:
For most use cases the order probably doesn’t matter… but what if the insertion order did matter?
In that case you would need to access the key/value pairs in an ordered way. You can do that by calling
Object.entries() on your objects to convert them to an array of key/value pair arrays.
For example, this:
Once you convert each object into an array of arrays, you can iterate through one of them checking to see whether every element in the comparison array at the same index is the same.
As before, we’re still using recursion (on line 11 in the above example) if we run into a value that is itself an object.