2 回答

TA貢獻1802條經驗 獲得超10個贊
你可以試試這個:
function showDepth(obj, lvl){
if(!lvl) lvl = 0;
Object.keys(obj).map(key => {
console.log(key + ' is in level ' + lvl);
if(typeof obj[key] === "object") {
showDepth(obj[key], lvl+1);
}
});
}
showDepth({
hi : "everyone",
hereIs : {
an : "Object"
}
});

TA貢獻1836條經驗 獲得超3個贊
您可以使用JSON.stringify'sreplacer如下:
const obj = {
hi: "everyone",
hereIs: {
an: "Object",
and: {
another: "one"
}
}
}
let level = -1;
JSON.stringify(obj, function(k, v) {
if (level >= 0)
console.log(k, "is in level", level);
if (typeof v == "object")
level++;
return v;
});
添加回答
舉報