JavaScript如何根据ParentId将扁平JSON转换为父子嵌套JSON结构
扁平结构JSON转Kendo TreeList嵌套层级实现
针对接口返回的带ParentId关联字段的扁平数组,可直接使用下面的转换函数生成符合要求的父子嵌套结构,子节点默认挂载在employees字段下,完全匹配Kendo TreeList的视图数据要求。
转换函数实现
/** * 扁平数组转嵌套树结构 * @param {Array} flatList 接口返回的扁平结构数据 * @returns {Array} 嵌套层级结构数组 */ function buildTree(flatList) { // 浅拷贝原始数据,避免修改接口返回的原对象 const nodeList = flatList.map(item => ({ ...item })); const nodeMap = new Map(); const tree = []; // 第一次遍历:所有节点存入哈希表,初始化子节点容器 nodeList.forEach(node => { node.employees = []; nodeMap.set(node.IdChild, node); }); // 第二次遍历:按关联字段挂载父子关系 nodeList.forEach(node => { const parentId = node.ParentId; // ParentId为null的是根节点,直接放入最终结果数组 if (parentId === null) { tree.push(node); return; } // 匹配到父节点时,将当前节点挂到父节点的employees数组下 if (nodeMap.has(parentId)) { const parentNode = nodeMap.get(parentId); parentNode.employees.push(node); } }); // 可选:清理叶子节点的空employees字段,和示例目标结构完全对齐 function clearEmptyEmployees(nodes) { nodes.forEach(node => { if (node.employees.length === 0) { delete node.employees; } else { clearEmptyEmployees(node.employees); } }) } clearEmptyEmployees(tree); return tree; }
使用示例
// 接口返回的原始扁平数据 const flatEmployees = [ { "id": 1, "IdChild": 23890952, "ParentId": null }, { "id": 2, "IdChild": 23890953, "ParentId": 23890952 }, { "id": 3, "IdChild": 23890954, "ParentId": 23890953 } ]; // 执行转换得到嵌套结构 const employees = buildTree(flatEmployees); export default employees;
注意事项
- 实现采用哈希表做节点索引,整体时间复杂度为O(n),仅需两次线性遍历即可完成转换,千级以上数据量也不会出现性能问题
- 关联逻辑严格匹配当前数据结构:子节点的
ParentId字段与父节点的IdChild字段做关联,不会出现层级挂载错误 - 如果后续需要修改子节点的挂载字段名,直接替换代码中所有
employees字段为目标字段名即可(比如children、items) - 内置的空字段清理逻辑为可选,若Kendo TreeList要求必须存在子级字段,删掉
clearEmptyEmployees相关调用即可
内容的提问来源于stack exchange,提问作者aa123
相关产品推荐
相关产品推荐

