如何在循环中为对象数组中非最高paid值的对象添加折扣标记
给数组中除paid最高项外的对象添加discount属性
实现步骤
- 先找出数组中所有对象的
paid字段最大值 - 遍历数组,给所有
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
相关产品推荐
相关产品推荐

