iT邦幫忙

0

請問如何從結構化陣列建立出樹元件?

  • 分享至 

  • xImage

我有以下資料

{
    "obj": ["2022","2022","2022","2023","2023","2023"],
    "obj1": ["PPP","PPP","AAA","AAA","CCC","CCC"],
    "obj2": [0,1,2,3,4,5]
}

資料中每個 index 互相對應,如"2022=>PPP=>0", "2022=>PPP=>1"...等. 資料階層是由key是obj -> obj1 -> obj2,有個陣列專門設定資料階層

var hierachyLevel = ["obj", "obj1", "obj2"]; //可動態變化,對應資料的key名稱

預期輸出:

categories: [
  {
    name: "2022",
    categories: [
      {
        name: "PPP",
        categories: [
          "0",
          "1"
        ]
      },
      {
        name: "AAA",
        categories: [
          "2"
        ]
      }
    ]
  },/////////////////////
  {
    name: "2023",
    categories: [
      {
        name: "AAA",
        categories: [
          "3"
        ]
      },
      {
        name: "CCC",
        categories: [
          "4",
          "5"
        ]
      }
    ]
  }
]

目前嘗試這個解法,以及自己寫無法解
如可幫忙非常感謝

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2023-04-29 15:56:33

參考這篇寫出以下

const tst = '{"obj":["2022","2022","2022","2023","2023","2023"],"obj1": ["PPP","PPP","AAA","AAA","CCC","CCC"],"obj2": [0,1,2,3,4,5]}';

const myObj = JSON.parse(tst);
document.getElementById("demo").innerHTML = myObj.obj[0];

console.log(myObj);

再參考那篇進行一些修改

我要發表回答

立即登入回答