Vue2中如何将REST API返回的嵌套对象数组转换为指定结构?
REST API返回数据结构转换方案
原代码问题点
- 初始化的
formattedResponse为数组类型,直接给数组挂载title/name等属性不符合目标结构要求 - 遍历过程中取值误用了整个
response数组,而非当前遍历项el - 未对子节点的字段做映射转换,也未按照要求生成对应key值
实现代码
created() { getData().then(response => { const formattedResponse = [] // 仅调用一次forEach完成全部转换逻辑 response.forEach((el, index) => { const parentNode = { title: el.Title, value: el.Name, key: String(index + 1), children: [] } // 同一次遍历内处理子节点映射,无需额外forEach if (Array.isArray(el.Children) && el.Children.length) { parentNode.children = el.Children.map((child, childIndex) => ({ title: child.Title, value: child.Name, key: `key${index + 1}-${childIndex + 1}` // 若需子节点key按全局序号排序可自行调整规则,比如`key${index + 1}${childIndex + 1}` })) } formattedResponse.push(parentNode) }) // 此处可将formattedResponse赋值给vue实例的data变量使用 // 若外层仅需单个根对象,直接取 formattedResponse[0] 即可 }) }
逻辑说明
- 完全匹配目标结构的字段映射规则:将原数据
Title字段映射为title,Name字段映射为value - key生成规则可根据业务需求灵活调整,示例规则保证了所有节点key的唯一性
- 仅使用1次forEach循环,子节点通过map做字段转换,符合性能要求
内容的提问来源于stack exchange,提问作者yeeterson
相关产品推荐
相关产品推荐

