I am trying to loop through the below JSON data, extract the total_price
field, sum it, then add the amount
field, found in refunds[<i>].transactions
array. As mentioned below I’m able to grab the total_price
fields and sum, however am lost on how to also grab and sum the refund amount
fields, which will be used to subtract from the total_price
sum.
JSON:
{
"sales_mtd": {
"orders": [
{
"created_at": "2021-06-25T16:30:47-04:00",
"fulfillment_status": null,
"name": "#1099",
"refunds": [
{
"admin_graphql_api_id": "gid://shopify/Refund/800483278870",
"created_at": "2021-06-25T19:18:05-04:00",
"duties": [],
"id": 800483278870,
"note": "",
"order_adjustments": [],
"order_id": 4071975550998,
"processed_at": "2021-06-25T19:18:05-04:00",
"refund_line_items": [],
"restock": true,
"total_duties_set": {
"presentment_money": {
"amount": "0.00",
"currency_code": "CAD"
},
"shop_money": {
"amount": "0.00",
"currency_code": "CAD"
}
},
"transactions": [
{
"admin_graphql_api_id": "gid://shopify/OrderTransaction/5016768315414",
"amount": "75.71",
"authorization": null,
"created_at": "2021-06-25T19:18:05-04:00",
"currency": "CAD",
"device_id": null,
"error_code": null,
"gateway": "manual",
"id": 5016768315414,
"kind": "refund",
"location_id": null,
"message": "Refunded 75.71 from manual gateway",
"order_id": 4071975550998,
"parent_id": 5015934074902,
"processed_at": "2021-06-25T19:18:05-04:00",
"receipt": {},
"source_name": "1830279",
"status": "success",
"test": false,
"user_id": 64086245398
}
],
"user_id": 64086245398
}
],
"total_price": "75.71"
},
I used this code to loop through the total_price
fields and sum them, thanks to help in another question.
let sumReduce = json.sales_mtd.orders.reduce((acc, curr) => acc + Number(curr.total_price), 0);
console.log(sumReduce);
However, when I try and repurpose this to also grab and sum the refund amounts, I either get NaN
or an error message unable to read the transaction or other field. I have tried reviewing MDN docs, starting from a less complex object, repurposing other answers but can’t quite seem to get it. Any input is very much appreciated.
Thank you
2
Answers
It looks like to me "transactions" is only available within the refunds array, and sometimes it is empty.
something like
if(refunds.length)
will do the jobTry the following:
sumReduce1
andsumReduce2
do the same thing for the JSON object you provide only thatsumReduce2
take into consideration that you can have multiple orders, refunds and transactions.sumReduce1
is more of a hard coded function, I would advise usingsumReduce2
.