如何用JavaScript(ES6)转换后端请求体为指定对象数组
转换请求体格式的ES6实现
问题描述
原始请求体:
{ "appId": "10001", "upstream": [ { "name": "john", "content": "APPLICATION 1" }, { "name": "peter", "content": "APPLICATION 2" } ], "downstream": [ { "name": "max", "content": "APPLICATION 3" }, { "name": "justin", "content": "APPLICATION 4" } ] }
需要转换为以下数组格式:
[ { "appId": "10001", "name": "john", "content": "APPLICATION 1", "type": "upstream" }, { "appId": "10001", "name": "peter", "content": "APPLICATION 2", "type": "upstream" }, { "appId": "10001", "name": "max", "content": "APPLICATION 3", "type": "downstream" }, { "appId": "10001", "name": "justin", "content": "APPLICATION 4", "type": "downstream" } ]
解决方案
利用ES6的对象解构、Object.entries、flatMap和扩展运算符实现,代码如下:
const transformRequestBody = (originalData) => { const { appId, ...rest } = originalData; return Object.entries(rest).flatMap(([type, items]) => { return items.map(item => ({ appId, ...item, type })); }); }; // 示例调用 const originalData = { "appId": "10001", "upstream": [ { "name": "john", "content": "APPLICATION 1" }, { "name": "peter", "content": "APPLICATION 2" } ], "downstream": [ { "name": "max", "content": "APPLICATION 3" }, { "name": "justin", "content": "APPLICATION 4" } ] }; const result = transformRequestBody(originalData); console.log(JSON.stringify(result, null, 2));
代码说明
- 对象解构提取
appId,剩余字段(upstream和downstream)存入rest Object.entries(rest)将字段名与对应数组转换为[类型名, 数据数组]的键值对集合flatMap将不同类型下的转换结果合并为一个扁平数组,避免嵌套- 对每个数据项,用扩展运算符合并
appId、原项数据和type字段
内容的提问来源于stack exchange,提问作者sourabh
相关产品推荐
相关产品推荐

