JS 递归处理树结构数据

327 阅读1分钟

背景:最近在做bpm系统,就是用各种组件拖拽生成模版页面,从而避免了每加个模版都需要研发去写页面了,但是拖拽实现的过程也是很艰辛的。有pc端和移动端的实现。话不多说。 新增需求,可隐藏控件和标题。 最优解就是从数据层面处理,把需要隐藏的数据处理掉,不去做渲染。

code

/* eslint prefer-arrow-callback: ["error", { "allowNamedFunctions": true }] */

const filterTree = (data) => {
  const newTree = data.filter(x => x.config.hide_component !== true).map(
    function replaceLabel(e) {
      e.label = e.config.hide_label === true ? '' : e.label; //隐藏label就传空
      return e;
    },
  );
  // newTree.forEach(x => x.children && (x.children = filterTree(x.children)));
  newTree.forEach(function loop(x) {
    x.children && (x.children = filterTree(x.children));
  });
  return newTree;
};

由于开的eslint箭头函数不让返回函数等等,就做了处理,且加了忽略规则 若是没有eslint可用箭头简写