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

如何在循环中为对象数组中非最高paid值的对象添加折扣标记

给数组中除paid最高项外的对象添加discount属性

实现步骤

  1. 先找出数组中所有对象的paid字段最大值
  2. 遍历数组,给所有paid值不等于最大值的对象添加discount: true属性

代码示例(修改原数组)

var booking = [
  {id:1,paid:200,currency:'USD'},
  {id:2,paid:99,currency:'USD'},
  {id:3,paid:100,currency:'USD'},
];

// 1. 获取paid的最大值
const maxPaid = Math.max(...booking.map(item => item.paid));

// 2. 遍历数组添加属性
booking.forEach(item => {
  if (item.paid !== maxPaid) {
    item.discount = true;
  }
});

console.log(booking);

执行后得到的结果就是你期望的数组:

[
  {id:1,paid:200,currency:'USD'},
  {id:2,paid:99,currency:'USD',discount:true},
  {id:3,paid:100,currency:'USD',discount:true},
]

不修改原数组的版本(返回新数组)

如果你不想改动原数组,可以用map方法生成新数组:

var booking = [
  {id:1,paid:200,currency:'USD'},
  {id:2,paid:99,currency:'USD'},
  {id:3,paid:100,currency:'USD'},
];

const maxPaid = Math.max(...booking.map(item => item.paid));
const updatedBooking = booking.map(item => {
  return item.paid !== maxPaid 
    ? {...item, discount: true} 
    : {...item};
});

console.log(updatedBooking);

这个版本会保留原数组不变,返回一个新的处理后的数组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:50:51