Home > Mobile >  How to get the total value from a object in react base on the created at date
How to get the total value from a object in react base on the created at date

Time:12-22

I need to get the sum of the item_subtotal_amount based on the created_at date.

const test = {
"id": 1414,
"integration_id": null,
"business_upstream_identifier": null,
"alternate_business_id": null,
"status": {
    "type": "ordered",
    "name": "Ordered"
},
"payment_term": null,
"payment_status_id": null,
"payment_status": null,
"payment_status_note": null,
"item_subtotal_amount": 3795,
"rounding_amount": 0,
"total_amount": 3795,
"created_at": "2022-12-19T23:02:25 00:00",}

there is a list of objects similar to this with different create_at dates like this. I need to get the sum of the item_subtotal_amount for a specific date.(created_at)

this is what I tried.

    let newTotal = 0
    test?.forEach((stat) => {
       newTotal  = stat.item_subtotal_amount;
    });

But this method is not working as expected because this is an object I am unable to loop. is there any other proper way I can use to achieve my goal?

CodePudding user response:

The snippet below solves your problem. I'm assuming that you only want to add a test's subtotal if it matches a given date regardless of what time it was created at during said date.

let testArray = [
  {"item_subtotal_amount": 100, "created_at": "2022-12-19T23:02:25 00:00"},
  {"item_subtotal_amount": 100, "created_at": "2021-11-20T23:11:52 00:00"},
  {"item_subtotal_amount": 100, "created_at": "2002-11-12T23:14:34 00:00"},
  {"item_subtotal_amount": 100, "created_at": "2022-12-19T23:32:53 00:00"},
  {"item_subtotal_amount": 100, "created_at": "2022-12-19T23:02:25 00:00"},
];

//I'm assuming that you want the date only and not the time
let chosenDate = "2022-12-19";
let sum = 0;

testArray.forEach((test) => {
  if (test.created_at.substring(0, 10) == chosenDate) {
    sum  = test.item_subtotal_amount;
  }
});

console.log(sum);

CodePudding user response:

This method worked for me to calculate the total.

const totalPerDay = Object.values(transactionList?.data.reduce((resMap, obj) => {
  const date = new Date(obj.created_at).toLocaleString().split(',')[0]

  if (resMap[date] !== undefined)
    resMap[date]  = obj.item_subtotal_amount
  else
    resMap[date] = obj.item_subtotal_amount

  return resMap;
}, {}))

reduce() - executes the given function for each value from left to right.

reduce() - does not change the original array.

The Object.values() method returns an array of a given object's own enumerable string-keyed property values.

  • Related