I’m looking for a function that compares two values. These values may or may not be objects. If they happen to be objects, I expect this function to verify that both objects have the same number of properties and that each property is contained in both. Lastly the function calls itself to evaluate each pair of properties. If they hold different values the function should return false.
let obj1 = {
a: 1,
b: "2",
c: { d: 2 }
};
let obj2 = {
a: 1,
b: "2",
c: { d: 2 }
};
let obj3 = {
a: 0,
b: "2",
c: { d: 2 }
};
let obj4 = {
a: 0,
b: "2",
c: {
d: 2,
e: { f: "A" }
}
};
function deepEqual(a, b) {
if (typeof a == 'object' && a != null && typeof b == 'object' && b != null) {
if (Object.keys(a).length == Object.keys(b).length) {
for (let i = 0; i < Object.keys(a).length; i += 1) {
if (Object.keys(b).includes(Object.keys(a)[i])) {
console.log(Object.keys(a)[i] + ": " + a[Object.keys(a)[i]] + ", " + Object.keys(a)[i] + ": " + b[Object.keys(b)[i]]);
deepEqual(a[Object.keys(a)[i]], b[Object.keys(a)[i]]);
} else {
return false;
}
}
} else {
return false;
}
} else if (a === b) {
return true;
} else {
return false;
}
}
Calling deepEqual
with any pair of aforementioned objects doesn’t have the expected result. For starters the function returns undefined
and never seems to reach the majority of the if (...) else
blocks. I’m not looking for a solution but perhaps a hint that might indicate what went wrong.
What works:
Calling deepEqual
on arbitrary values.
deepEqual(3, 4)
false
deepEqual(3, 3)
true
Recursion works too. If I pass deepEqual
objects containing nested objects, console.log
outputs their respective values.
deepEqual(obj1, obj2)
a: 1, a: 1
b: 2, b: 2
c: [object Object], c: [object Object]
d: 2, d: 2