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 ?

1
  • 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 for looping through arrays.) The outer map could make sense, if you return the sum from the callback and use its return value. Commented Mar 26, 2021 at 8:18

1 Answer 1

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));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.