You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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));

代码说明

  1. 对象解构提取appId,剩余字段(upstream和downstream)存入rest
  2. Object.entries(rest)将字段名与对应数组转换为[类型名, 数据数组]的键值对集合
  3. flatMap将不同类型下的转换结果合并为一个扁平数组,避免嵌套
  4. 对每个数据项,用扩展运算符合并appId、原项数据和type字段

内容的提问来源于stack exchange,提问作者sourabh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 10:06:25