如何合并并按Key分组映射JSON对象数组?附示例需求
解决JSON对象数组的键映射与转换问题
针对你提出的需求,核心是将原始数据中items数组内的对象,用外层的columnN对应值作为新键,替换原有的column1/column2等键名,生成符合预期的新对象数组。以下是具体实现方案(以JavaScript为例):
原始数据(修正JSON语法规范)
{ "List": [ { "column1": "Name", "column2": "Gender", "column3": "Phone", "column4": "Age", "items": [ { "column1": "SR", "column2": "M", "column3": "1223322", "column4": "23" }, { "column1": "SA", "column2": "F", "column3": "1322222", "column4": "26" } ] } ] }
实现步骤与代码
- 提取表头映射:从
List的第一个元素中,生成columnN到目标键名的映射表 - 遍历
items数组,逐个转换对象的键名 - 收集转换后的对象,得到最终结果
// 原始数据 const rawData = { "List": [ { "column1": "Name", "column2": "Gender", "column3": "Phone", "column4": "Age", "items": [ { "column1": "SR", "column2": "M", "column3": "1223322", "column4": "23" }, { "column1": "SA", "column2": "F", "column3": "1322222", "column4": "26" } ] } ] }; // 生成column到目标键的映射表 const headerMap = {}; const targetList = rawData.List[0]; for (const key in targetList) { if (key.startsWith('column') && key !== 'items') { headerMap[key] = targetList[key]; } } // 转换items数组 const transformedResult = targetList.items.map(item => { const newObj = {}; for (const key in item) { if (headerMap[key]) { newObj[headerMap[key]] = item[key]; } } return newObj; }); console.log(transformedResult);
运行结果
[ {"Name": "SR", "Gender": "M", "Phone": "1223322", "Age": "23"}, {"Name": "SA", "Gender": "F", "Phone": "1322222", "Age": "26"} ]
扩展说明
如果List数组包含多个表头+items组合,只需遍历rawData.List,对每个元素重复上述转换逻辑,再将结果合并即可。这种写法无需硬编码column1到column4,支持任意数量的列扩展。
内容的提问来源于stack exchange,提问作者Always Learn
相关产品推荐
相关产品推荐

