数组转成树结构

/* 
 * 此方法将改变原始数组
 * id: 唯一标识
 * pid: 对应父级id
 * children: 子元素对应的字段
*/
const construct = (list, id, pid, children) => {
  const map = new Map();
  const result = []
  
  list.forEach(item => {
    map.set(item[id], item)
  })
  
  list.forEach(item => {
    const parent = item[pid];
    if (parent) {
      const pNode = map.get(parent);
       if (!pNode[children]) pNode[children] = [];
       pNode[children].push(map.get(item[id]))
    } else {
      result.push(map.get(item[id]))
    }
  })
  
  return result;
}

优化版:

See the Pen JS 编程题 – 如何将数组转成树 by hjoker (@hjoker) on CodePen.