JavaScript树形结构转指定格式扁平数组问题求助
树形结构数组转换解决方案
问题描述
我有如下树形结构的JavaScript数组:
const data = [ { key: 1010, children: [ { key: 10101, children: [] }, { key: 10102, children: [ { key: 1010101, checked: false, }, { key: 1010102, checked: false, }, ], }, ], }, { key: 2020, children: [ { key: 20201, children: [ { key: 202020, checked: false, }, { key: 202021, checked: false, }, ], }, ], }, ];
希望得到如下格式的输出:
const output = { idsGrid: [ { gridId: 10101, isTable: false, }, { gridId: 10102, isTable: false, }, { gridId: 1010101, isTable: true, }, { gridId: 1010102, isTable: true, }, { gridId: 20201, isTable: false, }, { gridId: 202020, isTable: true, }, { gridId: 202021, isTable: true, }, ], };
具体需求
- 提取原数据中二级及以下的所有节点并整合为一个数组
isTable属性规则:当节点存在checked属性且值为false时,isTable设为true;否则设为false
我尝试用递归实现但没成功,当前代码如下:
console.log('data ==>',data) let a = [] const v = data.map(e => { return e.children.map(child => { return a.push({key : child.key,isTable : true}) }) } )
寻求正确的实现方案。
解决方案
可以用递归函数遍历所有二级及以下的节点,判断每个节点的checked属性来设置isTable,具体实现如下:
function convertTreeData(data) { const idsGrid = []; // 递归遍历节点 function traverseNodes(nodes) { nodes.forEach(node => { // 处理当前节点:添加到结果数组 idsGrid.push({ gridId: node.key, isTable: 'checked' in node && node.checked === false }); // 如果有子节点,继续递归遍历 if (node.children && node.children.length > 0) { traverseNodes(node.children); } }); } // 从一级节点的子节点(二级节点)开始遍历 data.forEach(item => { if (item.children && item.children.length > 0) { traverseNodes(item.children); } }); return { idsGrid }; } // 使用示例 const output = convertTreeData(data); console.log(output);
代码说明
- 递归遍历逻辑:定义
traverseNodes函数,遍历传入的节点数组,处理每个节点后,若存在子节点则继续递归遍历子节点 - 节点处理规则:
- 每个节点转换为
{ gridId: node.key, isTable: ... }格式 isTable通过'checked' in node && node.checked === false判断:只有当节点存在checked属性且值为false时,才设为true,否则为false
- 每个节点转换为
- 起始遍历点:从一级节点的
children(也就是二级节点)开始遍历,符合需求中“提取二级及以下所有节点”的要求
内容的提问来源于stack exchange,提问作者Tania12
相关产品推荐
相关产品推荐

