如何根据根据checkedKeys处理树形数据?

现有如下数据:

const treeData = [
  {
    title: '0-0',
    key: '0-0',
    children: [
      {
        title: '0-0-0',
        key: '0-0-0',
        children: [
          { title: '0-0-0-0', key: '0-0-0-0' },
          { title: '0-0-0-1', key: '0-0-0-1' },
          { title: '0-0-0-2', key: '0-0-0-2' },
        ],
      },
      {
        title: '0-0-2',
        key: '0-0-2',
      },
    ],
  },
  {
    title: '0-1',
    key: '0-1',
    children: [
      { title: '0-1-0-0', key: '0-1-0-0' },
      { title: '0-1-0-1', key: '0-1-0-1' },
      { 
        title: '0-1-0-2',
        key: '0-1-0-2',
        children: [
          {title: '0-1-0-2-0-0', key: '0-1-0-2-0-0'} 
        ]
      },
    ],
  },
];
const checkedKeys = ['0-0-0-1', '0-1-0-2-0-0'];

如何根据checkedKeys将treeData处理成如下数据:

[
  {
    title: '0-0',
    key: '0-0',
    children: [
      {
        title: '0-0-0',
        key: '0-0-0',
        children: [
          { title: '0-0-0-1', key: '0-0-0-1' },
        ],
      }
    ],
  },
  {
    title: '0-1',
    key: '0-1',
    children: [
      { 
        title: '0-1-0-2',
        key: '0-1-0-2',
        children: [
          {title: '0-1-0-2-0-0', key: '0-1-0-2-0-0'} 
        ]
      },
    ],
  },
]
阅读 2.1k
1 个回答
const result = ((roots, keysSet) => {
    // - roots,传入的 rootData
    // - keySets,从 checkedKeys 生成的集合对象,加速查找

    // 递归处理函数,处理一个节点数组,处理其中每一个节点,
    // - ① 如果该节点或其子节点被选中,返回该节点对应的数据 `{ key, title, children? }`
    // - ② 否则返回 null
    // - ③ 对所有直属子节点进行过滤,去掉 null
    function chooseNode(nodes) {
        return nodes
            // ①②
            .map(node => {
                // 若有子节点,递归处理
                // 按上述规则,返回的数组如果有元素,说明子孙级有节点被选中
                const children = node.children && node.children.length
                    ? chooseNode(node.children)
                    : [];
                
                // - 如果子孙级有节点被先中:children.length 有值且 >0
                // - 或者当前节点在 keysSet 中:keysSet.has(...)
                // ⇒ 那么当前节点被选中,生成对应的数据(新节点)
                if (children.length || keysSet.has(node.key)) {
                    const newNode = {
                        key: node.key,
                        title: node.title
                    };
                    if (children.length) {
                        newNode.children = children;
                    }
                    return newNode;
                }

                // 否则当前节点不需要选中,返回 null
                return null;
            })
            // ③
            .filter(node => node);
    }

    // 这是一切开始的地方
    return chooseNode(roots);
})(treeData, new Set(checkedKeys));

console.log(JSON.stringify(result, null, 4));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题