数组转树结构

  1. 递归

function dataToTree(list, parentId = 0) {
  return list
    .filter(item => item.cateParentId === parentId)
    .map(item => ({
      ...item,
      children: dataToTree(list, item.storeCateId)
    }));
}
  1. Map+循环

push的是对象的引用,所以是能够实现多层级的

function dataToTree(list) {
  const map = new Map();
  const roots = [];

  list.forEach(item => {
    map.set(item.storeCateId, { ...item, children: [] });
  });

  list.forEach(item => {
    const node = map.get(item.storeCateId);
    if (item.cateParentId && map.has(item.cateParentId)) {
      map.get(item.cateParentId).children.push(node);
    } else {
      roots.push(node);
    }
  });

  return roots;
}

树结构扁平化

  1. 递归处理

function treeToList(tree) {
  const result = [];
  const traverse = (nodes) => {
    for (const node of nodes) {
      const { children, ...rest } = node;
      result.push(rest);
      if (children && children.length) {
        traverse(children);
      }
    }
  };
  traverse(tree);
  return result;
}
  1. 迭代 + 栈实现

function treeToList(tree) {
  const stack = [...tree];
  const result = [];

  while (stack.length) {
    const node = stack.pop();
    const { children, ...rest } = node;
    result.push(rest);

    if (children && children.length) {
      stack.push(...children);
    }
  }

  return result;
}

数组去重by key

function uniqueByKey(arr, key) {
  const map = new Map();
  arr.forEach(item => {
    if (!map.has(item[key])) {
      map.set(item[key], item);
    }
  });
  return Array.from(map.values());
}