I'm trying to check if an object is another object's descendent. For example, obj2 is obj1's descendent:
const obj1 = {
a: 100,
b: {
c:{
d:100,
e:200,
f:3,
g:50,
h:10,
i:{
j:{
x:50,
y:100
}
}
}
}
}
const obj2 = {
i:{
j:{
x:50,
y:100
}
}
}
I try to use recursion to check this, but it's not correct. May I know where is the mistake? Thank you so much!
function isDescendent(obj1,obj2) {
//if both not object, compare their value
if (typeof obj1 !== 'object' && typeof obj2 !== 'object') {
return obj1 === obj2;
}
//if both object, compare their length first
if(Object.keys(obj1).length !== Object.keys(obj2).length) {
return false;
}
//if both object with the same length, loop and compare each key
for (let key in obj1) {
if(isDescendent(obj1[key],obj2)) {
return true;
}
}
return false;
}