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

2023-04-23  本文已影响0人  无题syl

原始数据

节点的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)
上一篇下一篇

猜你喜欢

热点阅读