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

如何使用forEach重构JSON Body并写入硬编码参数?

问题:使用forEach重构JSON并注入硬编码参数失败

我正尝试用forEach方法重构给定的JSON Body,同时添加一些硬编码参数,但始终没法按预期注入硬编码值。以下是我目前的实现代码:

let jsonBody = {
  items: [
    { name: "item1", price: 12.99 },
    { name: "item2", price: 9.99 },
    { name: "item3", price: 19.99 }
  ]
};

let newJsonBody = [];

jsonBody.items.forEach(function (item) {
  newJsonBody[item.name] = {
    name: item.name,
    price: item.price,
    appUrl: "https://apps.google.com/",
    stage: "accepted"
  };
});

console.log(newJsonBody);

我的期望结果如下:

{
    "inputs": [
        {
            "data": {
                "name": "item1",
                "price": 12.99,
                "appUrl": "https://apps.google.com/",
                "stage": "accepted"
            }
        },
        {
            "data": {
                "name": "item2",
                "price": 9.99,
                "appUrl": "https://apps.google.com/",
                "stage": "accepted"
            }
        },
        {
            "data": {
                "name": "item3",
                "price": 19.99,
                "appUrl": "https://apps.google.com/",
                "stage": "accepted"
            }
        }
    ]
}

解决方案

你的代码存在两个关键问题:

  • 错误地将newJsonBody声明为数组,却用对象键(item.name)赋值,数组应该通过push方法添加元素,而非键值对方式。
  • 未按照期望结构生成数据——每个元素需要被data字段包裹,你的代码直接生成了裸对象。

修正后的forEach实现

let jsonBody = {
  items: [
    { name: "item1", price: 12.99 },
    { name: "item2", price: 9.99 },
    { name: "item3", price: 19.99 }
  ]
};

// 初始化符合期望结构的对象,inputs为数组
let newJsonBody = { inputs: [] };

jsonBody.items.forEach(function(item) {
  // 生成带data字段的对象,推入inputs数组
  newJsonBody.inputs.push({
    data: {
      name: item.name,
      price: item.price,
      appUrl: "https://apps.google.com/",
      stage: "accepted"
    }
  });
});

console.log(newJsonBody);

更简洁的map实现

如果只是做数组转换,map方法比forEach更合适,代码更简洁:

let jsonBody = {
  items: [
    { name: "item1", price: 12.99 },
    { name: "item2", price: 9.99 },
    { name: "item3", price: 19.99 }
  ]
};

let newJsonBody = {
  inputs: jsonBody.items.map(item => ({
    data: {
      ...item, // 解构原item的属性,避免重复写name、price
      appUrl: "https://apps.google.com/",
      stage: "accepted"
    }
  }))
};

console.log(newJsonBody);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:35:55