如何用递归函数扁平化嵌套对象数组?现有代码问题求助
嵌套对象数组扁平化:修复递归遍历函数
我在处理数据展示任务时遇到嵌套数据结构的问题,需要编写递归函数遍历嵌套对象数组,将其重构为仅包含非object类型项的扁平数组。以下是原始结构、期望结构,以及我写的无法正常运行的代码,请求帮忙修正。
原始嵌套结构
[ { "key": "name", "value": "Johnweak", "title": "name", "type": "input" }, { "key": "lastname", "value": "weak", "title": "lastname", "type": "input" }, { "key": "cert", "value": "Certificate", "title": "Certificate", "type": "object", "children": [ { "key": "cert1", "value": "cert1", "title": "Certificate 1", "type": "object", "children": [ { "key": "cert1uni", "value": "cert1uni", "title": "Cert 1 University name", "type": "input" }, { "key": "cert1cgpa", "value": "cert1cpga", "title": "Cert 1 CGPA", "type": "input" } ] }, { "key": "cert2", "value": "cert2", "title": "Certificate 2", "type": "object", "children": [ { "key": "cert2uni", "value": "cert2uni", "title": "Cert 2 University name", "type": "input" }, { "key": "cert2cgpa", "value": "cert2cgpa", "title": "Cert 2 CGPA", "type": "input" } ] } ] }, { "key": "dob", "value": "2022-02-31", "title": "Date of birth", "type": "dropdown" } ]
期望的扁平结构
[ { "key": "name", "value": "Johnweak", "title": "name", "type": "input" }, { "key": "lastname", "value": "weak", "title": "lastname", "type": "input" }, { "key": "cert1uni", "value": "cert1uni", "title": "Cert 1 University name", "type": "input" }, { "key": "cert1cgpa", "value": "cert1cpga", "title": "Cert 1 CGPA", "type": "input" }, { "key": "cert2uni", "value": "cert2uni", "title": "Cert 2 University name", "type": "input" }, { "key": "cert2cgpa", "value": "cert2cpga", "title": "Cert 2 CGPA", "type": "input" }, { "key": "dob", "value": "2022-02-31", "title": "Date of birth", "type": "dropdown" } ]
当前无法运行的代码
const nestedArray = (array) => { let A = []; array.map((item) => { if((item.type === "object" && item.children) { Object.assign(A, item.children); nestedArray(A); } else { Object.assign(item); } } }
代码问题分析
- 语法错误:
if条件多了一个左括号,map方法和函数都缺少闭合括号。 - 逻辑错误:
- 用
Object.assign(A, item.children)合并数组是错误的,该方法用于对象合并,数组应使用扩展运算符或push。 - 递归调用未将返回结果合并到结果数组,只是传入了当前结果数组,没有有效收集子层级的扁平项。
else分支的Object.assign(item)无意义,未将当前项添加到结果数组。- 使用
map遍历却未利用其返回值,更适合用forEach处理遍历逻辑。
- 用
修正后的递归函数
const flattenNestedArray = (array) => { let result = []; array.forEach(item => { // 处理嵌套的object类型项,递归扁平化子数组并合并结果 if (item.type === "object" && item.children) { result = [...result, ...flattenNestedArray(item.children)]; } else { // 非object类型项直接加入结果数组 result.push(item); } }); return result; }
功能说明
- 用
forEach遍历数组,避免map带来的不必要数组创建。 - 遇到
type: "object"且包含children的项时,递归调用函数处理子数组,通过扩展运算符将递归返回的扁平数组合并到主结果中。 - 非
object类型的项直接push到结果数组,保留原始数据结构。 - 函数最终返回完整的扁平数组,完全匹配期望结构。
内容的提问来源于stack exchange,提问作者tedeeee
相关产品推荐
相关产品推荐

