扁平数组转tree

扁平数组转tree

需要用到的测试数据

let flatArr = [
  { id:1, title:'标题1', parent_id:0 },
  { id:2, title:'标题2', parent_id:0 },
  { id:3, title:'标题2-1', parent_id:2 },
  { id:4, title:'标题3-1', parent_id:3 },
  { id:5, title:'标题4-1', parent_id:4 },
  { id:6, title:'标题2-2', parent_id:2 },
]

使用 reduce 实现

const convert = (list)=>{
  const result = []
  const map = list.reduce((pre,cur)=>{
    pre[cur.id] = cur
    return pre
  },{})

  for(let item of list){
    if(item.parent_id === 0){
      result.push(item)
      continue
    }
    if(item.parent_id in map){
      const parent = map[item.parent_id]
      parent.childer = parent.childer || []
      parent.childer.push(item)
    }
  }
  return result
}

const res  = convert(flatArr)
console.time()
console.log(convert(flatArr));
console.timeEnd()

使用 filter 实现

const convert2 = (list)=>{
  const result = []
  list.forEach(r => {
    r.childer = list.filter(re=> re.parent_id === r.id)

    if(r.parent_id === 0){
      result.push(r)
    }
  });
  return result
}

console.time()
console.log(convert2(flatArr));
console.timeEnd()

Tree 转 扁平化数组

const flatten = (arr)=>{
  return arr.reduce((pre,cur)=>{
    const {id,title,parent_id,childer = []} = cur
    return pre.concat([{id,title,parent_id}], flatten(childer))
  },[])
}

console.log(flatten(res));

另一种思路

const listToTree = (list = [], id = 'id', pid = 'pid') => {
  const map = new Map()
  const newList = []

  list.forEach(item => {
    map.set(item[id], item)
  })

  list.forEach(item => {
    if (Number(item[pid]) === 0 || !map.get(item[pid])) {
      newList.push(item)
    }
    const v = map.get(item[pid])
    if (v) {
      if (Array.isArray(v.children)) {
        v.children.push(item)
      } else {
        v.children = [item]
      }
    }
  })
  return newList
}
posted @ 2023-02-08 23:33  咸鱼也要有理想  阅读(21)  评论(0)    收藏  举报
站长工具: