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

如何为JavaScript对象数组中所有Price字段值加1?

给数组对象的Price字段统一加1的解决方案

嘿,这个需求挺常见的,我给你分享两种实用的解决思路,你可以根据是否需要保留原数组来选择:

1. 使用Array.map()(推荐:不修改原数组)

如果不想改动原始数组的数据,map是最佳选择——它会返回一个全新的数组,完全不影响原数据,避免后续出现意外的副作用。

代码示例:

let arr = [ { "Id": 0, "Name": "Product 1", "Price": 10 }, { "Id": 0, "Name": "Product 1", "Price": 15 } ];

// 用map生成新数组,每个对象复制原属性后修改Price
let Final_arr = arr.map(item => ({
  ...item,
  Price: item.Price + 1
}));

console.log(Final_arr);
// 输出目标数组:
// [ { "Id": 0, "Name": "Product 1", "Price": 11 }, { "Id": 0, "Name": "Product 1", "Price": 16 } ]

这里用了对象扩展运算符...item来复制原对象的所有属性,再重写Price字段,确保原数组里的对象不会被修改,非常安全。

2. 使用Array.forEach()(直接修改原数组)

如果你确定不需要保留原数组的Price值,可以用forEach直接遍历修改原数组中的对象:

代码示例:

let arr = [ { "Id": 0, "Name": "Product 1", "Price": 10 }, { "Id": 0, "Name": "Product 1", "Price": 15 } ];

arr.forEach(item => {
  item.Price += 1;
});

// 此时arr就是你要的Final_arr
console.log(arr);

这种方式会直接修改原数组的内容,适合不需要保留原始数据的场景。

当然,你也可以用传统的for循环实现,逻辑和forEach一致:

let arr = [ { "Id": 0, "Name": "Product 1", "Price": 10 }, { "Id": 0, "Name": "Product 1", "Price": 15 } ];

for (let i = 0; i < arr.length; i++) {
  arr[i].Price += 1;
}

console.log(arr);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:11:52