js树结构转数组 扁平化 树结构平铺

tree数据扁平化

/**
* tree数据扁平化
* 添加深度
* 添加父级节点(不能添加,只能使用父节点ID,添加echart会爆栈)
*/
flatTree(data, treeMap = [], depth = 0) {
 if (!(data && data.length)) return;
 depth++;
 return data.reduce((acc, cur) => {
   cur.depth = depth;
   acc.push(cur);
   if (cur.children && cur.children.length) {
     this.flatTree(cur.children, treeMap, depth);
   }
   return acc;
 }, treeMap);
}

tree 铺平方法

// tree 铺平方法
const getNodeMap = (node, parentNode) => {
  node.parentNode = parentNode;
  const nodeMap = [node];
  if (node.children && node.children.length) {
    node.children.forEach(item => nodeMap.push(...getNodeMap(item, node)));
  }
  return nodeMap;
};

export const getTreeMap = tree => {
  if (!(tree instanceof Array)) return;
  const treeMap = [];
  tree.forEach(node => {
    treeMap.push(...getNodeMap(node, tree));
  });
  return treeMap;
};

获取树结构下某个字段的集合

const getProvilegeCode = data => {
  return data.reduce((acc, { resourceCode, children }) => {
    acc.push(resourceCode);
    if (children && children.length) acc.push(...getProvilegeCode(children));
    return acc;
  }, []);
};
const mutations = {
  updatePrivilege(state, data) {
    if (!(data.privilegeList && data.privilegeList.length)) return;
    state.privilegeCode = getProvilegeCode(data.privilegeList);
  }
};

你可能感兴趣的:(Javascript)