美文网首页
js 扁平化数组转成tree 结构数据

js 扁平化数组转成tree 结构数据

作者: 无题syl | 来源:发表于2023-04-23 10:20 被阅读0次

    原始数据

    节点的id 和可以确定父子关系的 parentId

    const treeData = [
      {
        id: '1',
        parentId: '',
        name: '红——水果',
        identity: '红方'
      },
      {
        id: '1-1',
        name: '红-水果-红色的',
        identity: '红方',
        parentId: '1'
      },
      {
        id: '1-1-1',
        name: '红-水果-红色的-苹果',
        identity: '红方',
        parentId: '1-1'
      },
      {
        id: '1-2',
        name: '红-水果-绿色的',
        identity: '红方',
        parentId: '1'
      },
      {
        id: '1-2-1',
        name: '红-水果-绿色的-西瓜',
        identity: '红方',
        parentId: '1-2'
      }
    ]
    
    

    listTotree

    function buildTree(data, parentId = '') {
      const tree = []
      for (const item of data) {
        if (item.parentId === parentId) {
          const children = buildTree(data, item.id)
          if (children.length) {
            item.children = children
          }
          tree.push(item)
        }
      }
      return tree
    }
    
    

    treeToList

    function flattenTree(tree, result = []) {
    for (const node of tree) {
      const { id, parentId, children, ...rest } = node
      result.push({ id, parentId, ...rest })
      if (children) {
        flattenTree(children, result)
      }
    }
    return result
    }
    
    const flatData = flattenTree(treeData)
    console.log(flatData)
    

    相关文章

      网友评论

          本文标题:js 扁平化数组转成tree 结构数据

          本文链接:https://www.haomeiwen.com/subject/zhnejdtx.html