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

如何在JS中将指定数据转换为API要求的目标格式?

数据转换解决方案

可以用JavaScript的Array.prototype.reduce()方法快速实现需求,将原数组按id2分组,把对应id3值归集到数组中,最终包裹在data1键下。

完整实现代码

// 原始输入数据
const originalData = [
  { id2: 79, id3: 18 },
  { id2: 79, id3: 19 },
  { id2: 80, id3: 30 }
];

// 执行转换
const transformedData = {
  data1: originalData.reduce((grouped, current) => {
    // 若当前id2未作为键存在,初始化空数组
    if (!grouped[current.id2]) {
      grouped[current.id2] = [];
    }
    // 将id3值添加到对应数组
    grouped[current.id2].push(current.id3);
    return grouped;
  }, {})
};

console.log(transformedData);

输出结果

{
  "data1": {
    "79": [18, 19],
    "80": [30]
  }
}

关键逻辑说明

  • reduce()是数组迭代工具,通过累计器grouped逐步构建目标对象。
  • 遍历每个元素时,先检查grouped中是否已有当前id2对应的键,没有则创建空数组。
  • 将当前元素的id3值推入对应数组,最终返回完成分组的对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:20:24