/**
 * 数组 转 Tree
 * @param {*} arr
 * @param {*} parent
 * @param {*} key
 * @returns
 */
export function arr2Tree(arr = [], parent = "parentId", key = "categaryId") {
  // 转换为字典
  const dict = arr.reduce((acc, item) => {
    return {
      ...acc,
      [item[key]]: {
        ...item,
        children: [],
      },
    };
  }, {});

  // 挂载父子节点
  const tree = [];
  for (let item of arr) {
    const it = dict[item[key]];
    const parentNodeId = it[parent];
    const parentNode = dict[parentNodeId];

    if (!parentNode) {
      tree.push(it);
    } else {
      dict[parentNodeId].children.push(it);
    }
  }
  
  return [tree, dict];
}
