Forgive me in advance if there's a similar question out there, but after a day of searching, I couldn't find what I need.
I'm calling an API that responds with data, and I've extracted the necessary details to create a JSON file with the following example:
{
"total": 563,
"shipping_fee": 58,
"e_charges": ???,
"order_items": [
{
"item_id": 6291020872,
"quantity": 1,
"price": 88,
"total": 88
},
{
"item_id": 7755274567,
"quantity": 1,
"price": 150,
"total": 150
},
{
"item_id": 7980571205,
"quantity": 1,
"price": 45,
"total": 45
},
{
"item_id": 12612977930,
"quantity": 1,
"price": 280,
"total": 280
}
]
}, ... {} {} {}....
My issue is calculating the total sum of all total
values in order_items []
, then adding the shipping_fee
and calculating two separate percentages.
- 10%
- 8%
It's important to note that I'm receiving these values in real-time.
const resDetails = await request.post(baseURL, {
data: viewData
});
info = await JSON.parse(JSON.stringify(await resDetails.json()));
Here is how the JSON file structure was derived:
orders = await info.data.orders.map((x) => ({total: x.order_items.map(y => Number(y.order_price) * y.amount).reduce((total, y) => y+total),
shipping_fee : Number(x.shipping_fee),
e_charges: Number(Number((x.order_items.map(y=> Number(y.order_price) * y.amount).reduce((total, y) => Number(y+total)) + Number(x.shipping_fee)) * 0.1).toFixed()),
order_items: x.order_items.map((y) => ({
item_id : y.item_id,
quantity: y.amount,
price: Number(y.order_price),
total: Number(y.order_price) * y.amount}))})
I managed to calculate the 10%, but I'm struggling to add the additional 8% without repeating the mapping, reducing, and adding the shipping_fee
again.
Number(Number((x.order_items.map(y=> Number(y.order_price) * y.amount).reduce((total, y) => Number(y+total)) + Number(x.shipping_fee)) * 0.1).toFixed())
I'm new to the world of JavaScript/TypeScript and I'm hoping for a more efficient way to achieve my goal. Thank you for any assistance.
EDIT: Here's the actual code: https://i.sstatic.net/bcHHI.png