I am working on a product, and I am trying to create a payload. I need total to be equal to totalPrice*taxRate. I tried doing this by:
total: selectedQuantities.reduce((a, c) => a + c.value * c.price, 0).reduce((m, n) => m * n.taxRate)
and by:
total: selectedQuantities.reduce((a, c) => a + c.value * c.price, 0) * devolucionItems.taxRate
Neither of these worked, and I really appreciate any help or advice with this, thank you!
Full Payload:
const returnPayload = {
...devolucionItems,
qty: totalQuantity,
seller: devolucionItems.user._id,
orderItems: devolucionItems.orderItems.map((item) => {
const result = selectedQuantities.find((selectedItem) => selectedItem.id === item._id);
return { ...item, qty: result.value, price: +result.price * +result.value, tax: result.tax};
}),
itemsPrice: selectedQuantities.reduce((a, c) => a + c.price, 0),
totalPrice: selectedQuantities.reduce((a, c) => a + c.value * c.price, 0),
taxRate: devolucionItems.taxRate,
total: selectedQuantities.reduce((a, c) => a + c.value * c.price, 0).reduce((m, n) => m * n.taxRate),
};```
I am not sure why it means that it is not working. In your calculation 2nd, reduce will not work.
I would suggest giving more context like the input object and what you get and what you expected etc. I was trying to create the context you can check below which is working fine as expected.
const devolucionItems = { taxRate:10 }
const selectedQuantities = [
{value: 1, price: 100},
{value: 1, price: 100},
{value: 1, price: 100},
]
const returnPayload = {
...devolucionItems,
itemsPrice: selectedQuantities.reduce((a, c) => a + c.price, 0),
totalPrice: selectedQuantities.reduce((a, c) => a + c.value * c.price, 0),
taxRate: devolucionItems.taxRate,
total: selectedQuantities.reduce((a, c) => a + c.value * c.price, 0) * (devolucionItems.taxRate / 100),
};
console.log(returnPayload);
Output:
{taxRate: 10, itemsPrice: 300, totalPrice: 300, total: 30}
10 % of 300 = 30