typescript遞歸遍歷

1、先定義一下數據類型

interface entity {
  id: any;
  label: string;
  children?: children[];
}

2、定義子級數據類型

interface children {
  id: any;
  label: string;
  children?: children[];
}

3、定義方法

const returnList = (list: entity) => {
  if (list.children && list.children.length) {
    list.id = 0
    list.label = list.label
    list.children.map(res => returnList(res))
  }
  return list;
}

4、定義一個默認的數據,一般是API獲取數據

const list = {
  id: 1,
  label: "父級",
  children: [{
    id: 2,
    label: "子級1",
    children: [{
      id: 3,
      label: "子級2"
    }]
  }]
}

5、輸出數據

const data: entity = returnList(list)

console.log(data)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章