I have to iterate these objects in order to check strict equality between them
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };
const obj3 = { a: 1, b: { c: 3 } };
What I have done, to make it work also with arrays is that:
function deepEqualityComparison(a, b) {
if (typeof a !== typeof b) {
return false;
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false;
}
return a.every(function(aKeys, index) {
return deepEqualityComparison(aKeys, b[index]);
});
}
if (typeof a === 'object' && a !== null && typeof b === 'object' && b !== null) {
const arrayA = Object.keys(a);
const arrayB = Object.keys(b);
if (arrayA.length !== arrayB.length) {
return false;
}
return arrayA.every(function(key, babbo) {
return deepEqualityComparison(a[key],b[key]);
});
}
return a === b;
}
I'm sure it is complicate and it could be done with less lines, but I have used only things I know or I understand at the moment.
My question is: for what I have understood creatng the variable keysA turns the object in an array but it loses the nested keys. So, when I use the "every(function()" it just iterates between keys a and b. In case b or other keys would have had more levels of nested keys, this code would not work, right?
Is there any mean to iterate nested keys in objects with multiple nested levels?
thank you
return arrayA.every(function(key, babbo) {
return deepEqualityComparison(a[key],b[key]);
});
I think this part is partially right but could be improved