树状结构数据转换

59 阅读1分钟

` let list = [ { id: '1', title: '节点1', parentId: '', }, { id: '1-1', title: '节点1-1', parentId: '1' }, { id: '1-2', title: '节点1-2', parentId: '1' }, { id: '2', title: '节点2', parentId: '' }, { id: '2-1', title: '节点2-1', parentId: '2' } ] console.log(list)

  function convert(list){
    const result = []
    let map = list.reduce((pre,cur) => {
      pre[cur.id] = cur
      return pre
    },{})
     
    for (let item of list ){
      if(item.parentId == ''){
        result.push(item)
       
      }
      if(item.parentId in map){
        const parent = map[item.parentId]
        parent.children =parent.children || []
        parent.children.push(item)
      }

    }
    return result
  }
  let res = convert(list)
  console.log(res)
  function flat(list){
    return  list.reduce((pre,cur) => {
      const {id ,title, parentId,children=[] } =cur
      return pre.concat([{id,title,parentId}],flat(children))
    },[])
   
  }
  console.log( flat(res))

`