如何将扁平化JSON转换为含3个对象的highlights数组?
扁平化JSON转数组对象的简便方法
问题描述
给定扁平化JSON响应:
{ "highlights.id": ["9ab80883-e8eb-4710-9818-e476fc32e356", "824ff2a0-1f17-44b7-b99f-ce227af12ea7", "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe"], "highlights.key": ["0", "1", "2"], "highlights.value": ["16\" Pedestal Fan", "High Quality Metal Grill ", "Heavy Duty Motor with 2000 RPM"], "highlights.productId": ["655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f"], "highlights.createdAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z"], "highlights.updatedAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z"] }
预期转换为数组嵌套对象的结构:
highlights: [ { id: "...", key: "...", value: "...", productId: "...", createdAt: "...", updatedAt: "..." }, { id: "...", key: "...", value: "...", productId: "...", createdAt: "...", updatedAt: "..." }, { id: "...", key: "...", value: "...", productId: "...", createdAt: "...", updatedAt: "..." } ]
但使用常规Unflatten库处理后,得到的是对象嵌套数组的结构:
highlights: { id: [], key: [], value: [], productId: [], createdAt: [], updatedAt: [] }
简便解决方案
无需依赖第三方库,直接通过遍历索引手动构建目标数组,代码简洁高效:
// 原始扁平化数据 const flatData = { "highlights.id": ["9ab80883-e8eb-4710-9818-e476fc32e356", "824ff2a0-1f17-44b7-b99f-ce227af12ea7", "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe"], "highlights.key": ["0", "1", "2"], "highlights.value": ["16\" Pedestal Fan", "High Quality Metal Grill ", "Heavy Duty Motor with 2000 RPM"], "highlights.productId": ["655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f"], "highlights.createdAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z"], "highlights.updatedAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z"] }; // 提取所有高亮字段的键名(去掉前缀"highlights.") const fieldKeys = Object.keys(flatData).map(key => key.replace('highlights.', '')); // 获取数据长度(假设所有数组长度一致) const itemCount = flatData["highlights.id"].length; // 构建目标数组 const result = { highlights: Array.from({ length: itemCount }, (_, index) => { return fieldKeys.reduce((obj, field) => { obj[field] = flatData[`highlights.${field}`][index]; return obj; }, {}); }) }; console.log(result);
代码说明
- 先提取所有字段名,去掉
highlights.前缀 - 以任意一个数组的长度作为循环次数(假设所有字段的数组长度相同)
- 用
Array.from生成对应长度的数组,每个元素通过reduce拼接当前索引下的所有字段值 - 最终得到预期的数组对象结构
如果需要过滤特定字段(比如只保留id、key、value、productId),只需修改fieldKeys的过滤逻辑:
// 只保留指定字段 const allowedFields = ['id', 'key', 'value', 'productId']; const fieldKeys = Object.keys(flatData) .map(key => key.replace('highlights.', '')) .filter(field => allowedFields.includes(field));
内容的提问来源于stack exchange,提问作者Kusal Lamsal
相关产品推荐
相关产品推荐

