0

Trying to make a simple deep comparison function and noticed that this block of code was returning false when it should be true. Added the console logs to find the flaw.

for(var prop in obj1){
    if(obj1[prop] !== obj2[prop]){
       console.log("obj1." + prop + " = " + JSON.stringify(obj1[prop]));
       console.log("obj2." + prop + " = " + JSON.stringify(obj2[prop]));
       return false;
    }
}

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

results are

obj1.here = {"is":"an"}
obj2.here = 1
false
obj1.here = {"is":"an"}
obj2.here = {"is":"an"}
false

So I can tell the for... in prop method seems to be working because it's comparing 'here' for example. This is good. I think they're equal in the second console.log, so I think the answer is to use a different way of comparing them, because it's still evaluating them by reference possibly?

Zack Lucky
  • 671
  • 3
  • 10
  • 25
  • You need to use recursion and apply your `for..in` comparison loop to object values you find, just like you're doing for the top-level objects. To put another way: if you expect structurally-identical objects (like `{is:"an"}` and a different `{is:"an")`) to compare equally, why did you write this function in the first place? – apsillers Jul 28 '16 at 15:03
  • Oh! You mean because 'here' is an object inside obj? – Zack Lucky Jul 28 '16 at 15:05
  • @ZackLucky it might help you looking at this post also: http://stackoverflow.com/questions/1068834/object-comparison-in-javascript – valanto Jul 28 '16 at 15:06

0 Answers0