You have a couple of issues; you should be traversing over the object, not its keys, and you should be checking if key === 'e'
, not target[key] !== 'e'
. Also, you should check that target[key]
is an object before attempting to traverse it:
const myObject = {
x: {
y: {
z: {
e: 'ddfg'
}
}
}
};
function traverse(target) {
for (const key in target) {
if (key !== 'e' && typeof target[key] === 'object') {
traverse(target[key]);
} else {
console.log(key, target[key]);
}
}
}
traverse(myObject);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…