js工具箱之树形结构和扁平化数据处理

337 阅读1分钟

在项目中,我们经常会遇到一些数据需要前端二次加工处理,比如tree树形结构数据扁平化处理、扁平化数组处理成tree树形结构。下面我们就来实现一下树形结构数据和扁平化数组的相互转换吧!

扁平化数组转为树形结构

/**
 * 扁平化数组转为树形结构
 * @param {*} list 元素数组
 * @param {*} parentId 父级id
 * @param {*} childrenProp 子集数组key名
 * @param {*} parentProp 父级节点key名
 * @param {*} idprop
 * @returns 返回数组
 */
export const listToTree = (
  list = [],
  parentId = '0',
  childrenProp = 'children',
  parentProp = 'parentId',
  idprop = 'id'
  //eslint-disable-next-line max-params
) => {
  let nodes = clone(list).filter(item => item[parentProp] === parentId)
  nodes.forEach(item => {
    if (!item[idprop]) {
      throw new Error(idProp + '属性不允许为空')
    }
    let childrenNodes = listToTree(list, item[idprop], childrenProp, parentProp, idProp)
    if (childrenNodes && childrenNodes.length) {
      item[childrenProp] = childrenNodes
    }
  })
  return nodes
}

tree结构数据扁平化处理


/**
 * tree结构数据扁平化处理
 * @param {*} tree
 * @param {*} childrenProp
 * @param {*} clone
 * @returns
 */
export const treeTolist = (tree, childrenProp = 'children', clone = true) => {
  if (!isArray(tree)) {
    //eslint-disable-next-line no-param-reassign
    tree = [tree]
  }
  let list = []
  let newTree = clone ? clone(tree) : tree
  newTree.forEach(item => {
    list.push(item)
    const childrenNodes = item[childrenProp]
    if (childrenNodes && childrenNodes.length) {
      list = [...list, ...treeTolist(childrenNodes, childrenProp), false]
    }
  })
  list.forEach(item => {
    delete item[childrenProp]
  })
  return list
}