Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
Sum array of objects with dynamic keys - Javascript

I've got the following array

arr = [
  { 'Atencion Personalizada': 2, 'Caja': 3 },
  { 'Atencion Personalizada': 1 },
  { 'Tarifa Social': 3 }
]

Expected output: 9

And I would like to sum the properties the shortest way possible. The thing is that the object keys are always variable so i can't go for:

arr.reduce((acc,item) => acc+item.keyName)

Found this post but can't adapt the code to my solution either:

var data = [{ A: 4, B: 2 }, { A: 2, B: 1 }, { A: 3, B: 1 }, { A: 2, B: 1, C: 1 }],
    result = data.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v), r), {});

Thank you in advance

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Here's my solution. Map through the array and flatten the properties values, then reduce them.

const arr = [
  { 'Atencion Personalizada': 2, 'Caja': 3 },
  { 'Atencion Personalizada': 1 },
  { 'Tarifa Social': 3 }
]

console.log(arr.flatMap(e => Object.values(e)).reduce((a, b) => a + b));

about 4 years ago · Juan Pablo Isaza Report

0

Use reduce twice, once on the outer array and once on the values of each object inside it.

const arr = [
  { 'Atencion Personalizada': 2, 'Caja': 3 },
  { 'Atencion Personalizada': 1 },
  { 'Tarifa Social': 3 }
];
const total = arr.reduce((gt, item) => 
  gt + Object.values(item).reduce((t, sub) => t + sub, 0)
, 0);

console.log(total);

about 4 years ago · Juan Pablo Isaza Report

0

Maybe something like this?

let acc = {};
for (let o of arr) for (let key in o) {
    acc[key] ??= 0;
    acc[key] += o[key];
}

Not a one-liner though

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!