看了好幾篇"數組"變"樹"的文章,我感受我要亮出個人祖傳老代碼了

話很少說直接貼碼,原創

效果arr=>tree

// 輸入arr
let arr = [
  {
    id: 10, // id
    pid: 5 // 父級id
  },
  {
    id: 1,
    pid: 2
  },
  {
    id: 3,
    pid: 4
  },
  {
    id: 2,
    pid: 3
  },
  {
    id: 100,
    pid: 5
  },
  {
    id: 10099,
    pid: 6
  },
  {
    id: 1000,
    pid: 100
  }
]
// 輸出tree
let tree = [
    {
        id:100
        pid: 5,
        c: [ // 子節點
            {
                id: 100,
                pid: 5,
                c: [
                    {
                        id: 1000,
                        pid: 100
                    }
                ]
            }
        ]
    }
]
//.........



複製代碼

性能無出其右(一千條數據在1ms左右)

靈感來源

let i = {
  a: []
}

i.a.push(i)
console.log(i)
複製代碼

實現

const obj = {}

arr.forEach((i, index) => {
  i.index = index
  obj[i.id] = i
})

arr.forEach((i, index) => {
  if (i.pid) {
    if (obj[i.pid]) {
      let pitem = arr[obj[i.pid].index]
      if (!pitem.c) pitem.c = []
      pitem.c.push(i)
      i.r = true
    }
  }
})

let newarr = arr.filter(i => !i.r)

console.log(newarr)
複製代碼
相關文章
相關標籤/搜索