js遍歷對象的層級(深度)以父級標題


let data = [
  {
    "score": 10,
    "items": [
      {
        "tit": "",
        "score": 10,
        "items": [
          {
            "tit": "知識",
            "score": 9,
            "items": [
              {
                "tit": "三角型",
                "score": 1,
                "items": []
              },
              {
                "tit": "平行四邊形",
                "score": 1,
                "items": []
              }
            ]
          },
          {
            "tit": "技能",
            "score": 1,
            "items": [
              {
                "tit": "邏輯",
                "score": 1
              },
              {
                "tit": "運算能力",
                "score": 1
              }
            ]
          },
          {
            "tit": "能力",
            "score": 0,
            "items": []
          }
        ]
      }
    ]
  }
];
(function ps(data, depth, ptit) {
  for (let v of data) {
    if (v.tit || '') {
      console.log(v.tit, depth, ptit)
    }
    if (v.hasOwnProperty('items') && v.items.length) {
      ps(v.items, depth + 1, v.tit);
    }
  }
})(data, 0, '');

result:

知識 2
三角型 3 知識
平行四邊形 3 知識
技能 2
邏輯 3 技能
運算能力 3 技能
能力 2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM