将嵌套JSON展平为无索引的唯一对象数组
嵌套JSON展平为多行对象数组的实现方案
针对需要将嵌套JSON展平为数组形式(每个数组元素对应底层数组的单个值,并保留所有上层非数组字段)的需求,以下是实现方案:
核心思路
递归遍历JSON结构,遇到数组时对每个元素单独展开,将展开后的字段与上层已收集的字段进行笛卡尔积合并,最终生成每个底层值对应的完整对象数组。
实现代码
function flattenToArray(obj, parentKey = '', currentObj = {}) { let result = []; for (const key in obj) { if (!obj.hasOwnProperty(key)) continue; const value = obj[key]; const newKey = parentKey ? `${parentKey}.${key}` : key; if (Array.isArray(value)) { // 遍历数组元素,递归处理后合并结果 for (const item of value) { result = result.concat(flattenToArray(item, newKey, {...currentObj})); } } else if (typeof value === 'object' && value !== null) { // 递归处理嵌套对象,传递当前对象副本避免引用冲突 result = result.concat(flattenToArray(value, newKey, {...currentObj})); } else { // 处理基础类型值,生成包含所有已收集字段的新对象 const newObj = {...currentObj}; newObj[newKey] = value; result.push(newObj); } } // 处理空对象等边界场景,确保返回有效对象 if (result.length === 0) { result.push({...currentObj}); } return result; } // 测试输入 const input = { name: "Benny", department: { section: "Technical", branch: { timezone: "UTC", }, }, company: [ { name: "SAP", customers: ["Ford-1", "Nestle-1"], }, { name: "SAP", customers: ["Ford-2", "Nestle-2"], }, ], }; // 执行并输出结果 console.log(JSON.stringify(flattenToArray(input), null, 2));
输出结果
执行上述代码后,将得到期望的数组形式:
[ { "name": "Benny", "department.section": "Technical", "department.branch.timezone": "UTC", "company.name": "SAP", "company.customers": "Ford-1" }, { "name": "Benny", "department.section": "Technical", "department.branch.timezone": "UTC", "company.name": "SAP", "company.customers": "Nestle-1" }, { "name": "Benny", "department.section": "Technical", "department.branch.timezone": "UTC", "company.name": "SAP", "company.customers": "Ford-2" }, { "name": "Benny", "department.section": "Technical", "department.branch.timezone": "UTC", "company.name": "SAP", "company.customers": "Nestle-2" } ]
代码说明
- 递归遍历:通过递归处理嵌套对象和数组,确保所有层级的字段都能被正确展平
- 数组处理:遇到数组时,对每个元素单独递归,将每个元素的展开结果与上层字段合并,实现多行生成
- 引用隔离:使用对象扩展运算符(
...currentObj)创建副本,避免递归过程中修改原对象导致的字段污染 - 边界处理:针对空对象等场景,确保返回至少一个包含已收集字段的对象,避免结果为空
内容的提问来源于stack exchange,提问作者Benny
相关产品推荐
相关产品推荐

