看了好几篇"数组"变"树"的文章,我感受我要亮出个人祖传老代码了

话很少说直接贴码,原创

效果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)
复制代码
相关文章
相关标签/搜索