树状结构

一次循环非递归生成树状结构

  const data = [
  {
    id: 1,
    parentId: 0,
    title: "0-1"
  },
  {
    id: 2,
    parentId: 0,
    title: "0-2"
  },
  {
    id: 11,
    parentId: 1,
    title: "1-1"
  },
  {
    id: 12,
    parentId: 1,
    title: "1-2"
  },
  {
    id: 21,
    parentId: 2,
    title: "2-1"
  }]

const generateTree = (list,
  rootId,
  { idName = 'id', parentIdName = 'parentId', childName = 'children' } = {}
) => {
  if (!Array.isArray(list)) {
    return list
  }
  const objMap = {}
  // 暂存数组以id为key的映射关系 
  const result = []
  // 结果
  for (const item of list) {
    const id = item[idName]
    const parentId = item[parentIdName]
    // 该元素有可能已经放入map中(找不到该项的parent时会先放入map)
    objMap[id] = !objMap[id] ? item : { ...item, ...objMap[id] }
    const treeItem = objMap[id]
    // 找到映射关系那一项(注意这里是引用)
    if (parentId === rootId) {
      //已经到根元素则将映射结果放进结果集 
      result.push(treeItem)
    } else {
      // 若父元素不存在,初始化父元素 
      if (!objMap[parentId]) { objMap[parentId] = {} }
      //若无该根元素则放入map中
      if (!objMap[parentId][childName]) {
        objMap[parentId][childName] = []
      }
      objMap[parentId][childName].push(treeItem)
    }
  }
  return result
}


const result = generateTree(data, 0)

console.log(result)

Contributors: --