
本文介绍如何使用递归方法将具有 children 属性的嵌套对象数组,转换为一种“层级展开式”结构:每个含 children 的节点原样保留,其子节点数组作为独立项紧随其后插入结果数组中,从而支持类似 Ant Design 表头分组的渲染逻辑。
本文介绍如何使用递归方法将具有 `children` 属性的嵌套对象数组,转换为一种“层级展开式”结构:每个含 `children` 的节点原样保留,其子节点数组作为独立项紧随其后插入结果数组中,从而支持类似 ant design 表头分组的渲染逻辑。
在构建高级表格组件(如支持多级表头分组的自定义 Table)时,常需将树形结构的数据转换为一种特殊的扁平序列——既不丢失原始层级信息,又能让 UI 层按需识别“父列”与“子列区块”。这种结构不同于完全扁平化(Flatten),而是保留父节点、显式追加其子节点数组,形成 [parent, [child1, child2, ...], nextParent, ...] 的混合格式。
下面是一个简洁、可复用的递归实现:
const flattenWithChildren = (nodes) => {
const result = [];
for (const node of nodes) {
// 始终先推入当前节点(保持原始结构)
result.push(node);
// 若存在 children,则递归处理,并将整个子数组作为一项追加
if (Array.isArray(node.children) && node.children.length > 0) {
result.push(flattenWithChildren(node.children));
}
}
return result;
};✅ 使用示例:
const base = [
{ name: "John" },
{ name: "Jane" },
{
name: "Tom",
children: [
{ name: "Jerry" },
{ name: "Mart" },
{
name: "Mary",
children: [{ name: "bob" }]
}
]
},
{ name: "boboy" }
];
const result = flattenWithChildren(base);
console.log(JSON.stringify(result, null, 2));? 输出结构说明(关键特征):
- 每个原始对象(如
{name: "Tom"})完整保留; - 其
children经递归处理后,作为一个新数组项紧跟其后(而非内联或丢弃); - 深层嵌套(如
"Mary"下的"bob")同样被递归展开,生成嵌套数组[ [{name:"bob"}] ],便于 UI 渲染时判断缩进层级。
⚠️ 注意事项:
- 该函数不修改原数据,返回全新结构,符合函数式编程规范;
-
children字段必须为数组类型且非空才触发递归,避免运行时错误; - 若需进一步转换为纯一维数组(如用于
<thead> 单行渲染),可在顶层调用 <code>result.flat(Infinity),但注意会丢失父子位置关联——因此本方案推荐在渲染层通过Array.isArray(item)动态识别“子列区块”; - 实际项目中,建议配合 TypeScript 类型定义(如
interface Column { name: string; children?: Column[] })提升可维护性。
此模式正是 Ant Design 等 UI 库中 columns 配置支持表头分组的核心数据约定。掌握它,你就能灵活构建具备多级表头、拖拽排序、动态折叠等能力的专业表格组件。

















