亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取對象中鍵的級別

獲取對象中鍵的級別

精慕HU 2021-11-04 17:37:13
現在我使用JSON Objects來比較信息,我不知道是否有辦法獲得特定鍵的深度級別。例如,我有這個 JSON 對象:{   hi : "everyone",   hereIs : {      an : "Object"   }}我需要在for ... in循環中知道每個鍵的深度級別:hi is in level 0hereIs is in level 0an is in level 1我目前所擁有的是: // Loop through the first object     for (key in obj1) {          if (obj1.hasOwnProperty(key)) {               compare(obj1[key], obj2[key], key);          }     }“比較”功能如果用來驗證對象中的信息是否相等,如果不相等,則將信息添加到第三個對象中,我想知道的是如何獲得 obj1 中的密鑰級別和將其傳遞給“比較”函數。感謝您的幫助。
查看完整描述

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"

   }

});


查看完整回答
反對 回復 2021-11-04
?
米脂

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;

});


查看完整回答
反對 回復 2021-11-04
  • 2 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號