Как вычислить сумму ключей объекта в массиве-javascript?
Как посчитать общую сумму orders.price отдельно для каждого объекта?
const orders = [
{
id: 1,
tableNum: 24,
waiter: 'Alisa',
orderedDate: '5:14',
orders: [
{title: 'Something', count: 2, price: 10000},
{title: 'Something', count: 1, price: 15000},
{title: 'Something', count: 1, price: 8000},
{title: 'Something', count: 2, price: 7000},
]
},
{
id: 2,
tableNum: 23,
waiter: 'Ivan',
orderedDate: '6:14',
orders: [
{title: 'Something', count: 2, price: 10000},
{title: 'Something', count: 1, price: 15000},
{title: 'Something', count: 1, price: 8000},
{title: 'Something', count: 2, price: 7000},
]
}
]
let total_sum = 0
orders.forEach((function(order){
order.orders.forEach((function(item){
total_sum += item.price
return total_sum
}))
console.log(total_sum)
total_sum = 0
}))
Ответы (3 шт):
Автор решения: OPTIMUS PRIME
→ Ссылка
orders.forEach(obj => obj.total = obj.orders.reduce((sum, order) => sum + order.price, 0));
Для каждого объекта obj в массиве, создает дополнительное поле total, куда записывает сумму всех .price из его .orders
const orders = [
{
id: 1,
tableNum: 24,
waiter: 'Alisa',
orderedDate: '5:14',
orders: [
{title: 'Something', count: 2, price: 10000},
{title: 'Something', count: 1, price: 15000},
{title: 'Something', count: 1, price: 8000},
{title: 'Something', count: 2, price: 7000},
]
},
{
id: 2,
tableNum: 23,
waiter: 'Ivan',
orderedDate: '6:14',
orders: [
{title: 'Something', count: 2, price: 10000},
{title: 'Something', count: 1, price: 15000},
{title: 'Something', count: 1, price: 8000},
{title: 'Something', count: 2, price: 7000},
]
}
];
orders.forEach(obj => obj.total = obj.orders.reduce((sum, order) => sum + order.price, 0));
console.log(orders);
Автор решения: DiD
→ Ссылка
А что там сложного?
let map = new Map(orders.map(({id,orders})=>
[id,orders.reduce((sum,{count,price})=>
sum+count*price,0
)]
));
console.log(map);
Автор решения: Yaant
→ Ссылка
Можно даже так, чтобы не пересчитывать каждый раз при изменении состава заказа:
const orders = [{
id: 1,
tableNum: 24,
waiter: 'Alisa',
orderedDate: '5:14',
orders: [{
title: 'Something',
count: 2,
price: 10000
},
{
title: 'Something',
count: 1,
price: 15000
},
{
title: 'Something',
count: 1,
price: 8000
},
{
title: 'Something',
count: 2,
price: 7000
},
]
},
{
id: 2,
tableNum: 23,
waiter: 'Ivan',
orderedDate: '6:14',
orders: [{
title: 'Something',
count: 2,
price: 10000
},
{
title: 'Something',
count: 1,
price: 15000
},
{
title: 'Something',
count: 1,
price: 8000
},
{
title: 'Something',
count: 2,
price: 7000
},
]
}
]
orders.forEach(order => {
Object.defineProperty(order, 'total', {
get: function() {
return this.orders.reduce((sum, order) => sum + order.price * order.count, 0);
}
})
});
console.log(orders[0].total)
orders[0].orders.push({
title: 'Something else',
count: 10,
price: 2000
})
console.log(orders[0].total)