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.
JavaScript
x
6
1
var booking = [
2
{id:1,paid:200,currency:'USD'},
3
{id:2,paid:99,currency:'USD'},
4
{id:3,paid:100,currency:'USD'},
5
]
6
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
JavaScript
1
6
1
var booking = [
2
{id:1,paid:200,currency:'USD'},
3
{id:2,paid:99,currency:'USD',discount:true},
4
{id:3,paid:100,currency:'USD',discount:true},
5
]
6
Advertisement
Answer
You could get max paid
value first and then apply the new property, if necessary.
JavaScript
1
6
1
const
2
booking = [{ id: 1, paid: 200, currency: 'USD' }, { id: 2, paid: 99, currency: 'USD' }, { id: 3, paid: 100, currency: 'USD' }],
3
max = Math.max(booking.map(({ paid }) => paid)),
4
result = booking.map(o => ({ o, o.paid === max || { discount: true } }));
5
6
console.log(result);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }