如何将JS嵌套对象中subItem字段批量重命名为children,是否有非递归方案?
JS嵌套字段统一重命名方案
需求说明
将多层嵌套对象中所有层级的subItem字段,统一重命名为children,支持递归及非递归两种实现方式。
方案1:递归实现(最简洁,常规场景优先用)
代码逻辑简单易维护,适合嵌套层级不超过JS调用栈上限(通常为10000层以内)的绝大多数业务场景:
const transformData = (data) => { return data.map(stat => { const { subItem, ...restProps } = stat; return { ...restProps, children: subItem ? transformData(subItem) : [] } }) }
方案2:非递归实现(无栈溢出风险,适合超深嵌套场景)
用队列做广度优先遍历,完全规避递归的栈溢出问题:
const transformData = (data) => { // 深拷贝避免修改原数据,不需要保留原数据可直接操作原数组 const result = JSON.parse(JSON.stringify(data)); const queue = [...result]; while (queue.length) { const currentNode = queue.shift(); // 存在subItem则重命名,同时把子节点推入队列待处理 if (currentNode.subItem) { currentNode.children = currentNode.subItem; delete currentNode.subItem; queue.push(...currentNode.children); } else { currentNode.children = []; } } return result; }
方案3:极简JSON替换实现(适合纯数据场景)
如果你的数据中不存在"subItem":格式的字符串内容、也没有JSON不支持的类型(函数、Symbol、循环引用、undefined等),可以用这种极简写法:
const transformData = (data) => { return JSON.parse(JSON.stringify(data).replace(/"subItem":/g, '"children":')) }
各方案对比
- 递归实现:代码量少、可读性最高,常规场景首选
- 迭代实现:性能稳定无栈溢出风险,适合嵌套层级极深的特殊场景
- JSON替换:代码最短性能高,仅适合纯数据且无冲突字符串的场景
内容的提问来源于stack exchange,提问作者DevOverflow
相关产品推荐
相关产品推荐

