0

I have a json in the below format

let newarrayObj = [
    {
    "cost one": "118",
    "cost two": "118",
    "cost three": "118"
    },
    {
    "cost one": "118",
    "cost two": "118",
    "cost three": "118"
   },
   {
    "cost one": "118",
    "cost two": "118",
    "cost three": "118"
   }
]

I need the sum of each object which is 118 + 188 + 118 = 424 and the sum of total which is 424 + 424 + 424 = 1272

approach so far :

Object.entries(newarrayObj).map(([key, value]) => {
    Object.values(value).map((j, i) => {
        console.log(j);
    })
})

how can i get the expected sum values ?

  • `map` won't give you a sum (even if you use the return value -- never use `map` if you're not using the return value!). See the linked question for how to get the sum of the values in the array you're getting from `Object.values`. (Re `map`: The only reason for using it is to make use the the array it creates and returns. It's **not** for looping through an array otherwise. See [this question's answers](https://stackoverflow.com/questions/9329446/) for looping through arrays.) The outer `map` could make sense, if you return the sum from the callback and use its return value. – T.J. Crowder Mar 26 '21 at 08:18

1 Answers1

1

You can .map over all array entries and then use .reduce on the Object.values of each array entry to sum the values:

let data = [
    {
    "cost one": "118",
    "cost two": "118",
    "cost three": "118"
    },
    {
    "cost one": "118",
    "cost two": "111",
    "cost three": "118"
   },
   {
    "cost one": "120",
    "cost two": "118",
    "cost three": "118"
   }
];

function sumValues(objArr) {
 return objArr.map(curr => {
   return Object.values(curr).reduce((prev, val) => prev += Number(val), 0)
 });
}

console.log(sumValues(data));
eol
  • 23,236
  • 5
  • 46
  • 64