I have array of object which have key paid. I want to apply discount on all objects expect object which paid value is higher using loop.
var booking = [
{id:1,paid:200,currency:'USD'},
{id:2,paid:99,currency:'USD'},
{id:3,paid:100,currency:'USD'},
]
On above array of object name booking
i want to make loop and apply discount by adding key discount:true
in that object except higher paid
value object.
This is what i want after loop
var booking = [
{id:1,paid:200,currency:'USD'},
{id:2,paid:99,currency:'USD',discount:true},
{id:3,paid:100,currency:'USD',discount:true},
]
CodePudding user response:
You could get max paid
value first and then apply the new property, if necessary.
const
booking = [{ id: 1, paid: 200, currency: 'USD' }, { id: 2, paid: 99, currency: 'USD' }, { id: 3, paid: 100, currency: 'USD' }],
max = Math.max(...booking.map(({ paid }) => paid)),
result = booking.map(o => ({ ...o, ...o.paid !== max && { discount: true } }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
You could use map
to return a new array with modified elements if the order meets a condition:
var res = booking.map( order => {
if (order.paid > 98) return { discount: true, ...order }
return order
});