Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
How could I sum a property of each object for separate object arrays?

I had an object which in it had objects which each had an array of objects with 0..n objects. The main object looked something like this:

{
    obj1: [{obj1.1}, {obj1.2}, {obj1.3}],
    obj2: [{obj2.1}]
    obj3: [{obj3.1}, {obj3.2}]
}

Each object (obj1, obj2 and obj3) held a group of common objects in an array of objects. E.g. obj1 has a group of objects in an object array (obj1.1, obj1.2 and obj1.3) all which have a common property that groups them together.

I want to now be able to iterate over each object separately in each object array in order to sum a particular property (which each object has) for each object array.

I have used Object.keys to iterate over each object array, although I still am unable to get a separate summed value per object array.

For example:

{
    obj1: [
       0: { price: 10 }
       1: { price: 10 }
       2: { price: 10 }
    ],
    obj2: [
       0: { price: 10 }
    ],
    obj3: [
       0: { price: 10 }
       1: { price: 10 }
    ]
}

I want to be able to sum the property price for each individual object array. Therefore for obj1 I should have a summed amount of 30. For obj2 I should have a summed amount of 10, and lastly for obj3 I should have a summed amount of 20.

I can iterate over each object array using Object.keys, however as it stands now, when iterating over each individual element in each object array (using a foreach), I am only summing a final amount for all objects in all three object arrays. I.e. I am getting a summed amount of 60.

var total = 0;
for (var key of Object.keys(result)) {
    result[key].forEach(element => {
        total += element.Price;
    });
};
console.log(total);

What could I use to get the three individually summed amounts per object array?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

function sum(prices)
{
  let total = 0;
  prices.forEach((entry) => total += entry.price);
  return total;
}

console.log(sum(obj1));
console.log(sum(obj2));
console.log(sum(obj3));

Why was this hard again? You had the right code, just needed to break things out.

about 4 years ago · Juan Pablo Isaza Denunciar

0

  • Using Object#entries, get the key-array pairs
  • Using Array#reduce, iterate over this list
  • In every iteration, using Array#reduce, you can calculate the total price and save it as a value for the current key

const data = {
  obj1: [ { price: 10 }, { price: 10 }, { price: 10 } ],
  obj2: [ { price: 10 } ],
  obj3: [ { price: 10 }, { price: 10 } ]
};

const res = Object.entries(data).reduce((totalMap, [key, arr]) => ({
  ...totalMap,
  [key]: arr.reduce((total, { price }) => total + price, 0)
}), {});

console.log(res);

about 4 years ago · Juan Pablo Isaza Denunciar

0

yet here another way to get the result as an array:

let obj={obj1:[{price:10},{price:10},{price:10}],obj2:[{price:10}],obj3:[{price:10},{price:10}]};


let result = Object.entries(obj)
    .map(([k,v]) =>  ( {[k]:v.reduce((acc,e) => acc+=e.price ,0)} ) )

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda