js 将数组列表转为树结构

    let list = [
      {
        id: '1',
        title: '节点1',
        parentId: '',
      },
      {
        id: '1-1',
        title: '节点1-1',
        parentId: '1'
      },
      {
        id: '1-2',
        title: '节点1-2',
        parentId: '1'
      },
      {
        id: '1-2-1',
        title: '节点1-2-1',
        parentId: '1-2'
      },
      {
        id: '1-2-1-1',
        title: '节点1-2-1-1末级',
        parentId: '1-2-1'
      },
      {
        id: '2',
        title: '节点2',
        parentId: ''
      },
      {
        id: '2-1',
        title: '节点2-1',
      parentId: '2'
      }
    ]
    // 重点在这几句
    // 通过info建立了id=>node的映射
    let info = list.reduce((map, node) => {
      return map[node.id] = node, node.children = [], map
    }, {})
    // 最后arr就是我们转换成功的树结构
    const arr = list.filter(node => {
      if (info[node.parentId]) {
        // 将对应的node放入对应的对象里面去,因为它是浅拷贝,所以会影响原来的数组
        // 进而组装成一个树结构,这块大家打印出来看看就明白了了
        info[node.parentId].children.push(node)
      }
      // 将没parentId的node返回组成一个新数组
      // 没有parentId代表着它是根元素
      return !node.parentId  // 为 true会返回这个数据,为false则不会返回
    })

转换后的效果

猜你喜欢

转载自blog.csdn.net/my_bo/article/details/112363335
今日推荐