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

163
Vistas
Add Value to Itself in ForEach Using Keys Javascript

I'm trying to loop thru an array and sum values for each Department in the array. See below. I'm trying to loop thru the objects and add all of the Money values (sum them) per Department.

var awards = [
  { Department: "AL", Money: 100 }, 
  { Department: "AL", Money: 100 },
  { Department: "OB", Money: 200 }, 
  { Department: "AL", Money: 100 },
  { Department: "OB", Money: 200 }
];

var myObj = {},
    array1 = [],
    sum = 0,
    array2 = [],
    myObj2 = {};
var activeDepartments = ["AL", "OB"];
//FOREACH
Object.keys(awards).forEach(function(key, index) {
    var department = awards[key].Department;
    var money = awards[key].Money;
    sum = 0;

    // console.log(this[index].Money);
    if (activeDepartments.indexOf(department) !== -1) {
        sum += this[index].Money;
        myObj[department] = sum;
    }
    //console.log(index);

}, awards);
array1.push(myObj); //PUSH OBJECT TO ARRAY
console.log(array1);

//trying to get object to look like this: [{AL:300}, {OB:400}]

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

0

Instead of sum = 0, you need sum = myObj[department] ?? 0;. This way, you don't resend the sum each iteration of the loop. What that line of code does is check if the expression to the left of ?? (myObj[department]) is defined. If it is, it assigns its value to sum. Otherwise, it assigns the value of the expression to the right of ??.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Similiar question has been already resolved in Sum similar keys in an array of objects

in your case the code would look like this

var awards = [
    { Department: "AL", Money: 100 }, 
    { Department: "AL", Money: 100 },
    { Department: "OB", Money: 200 }, 
    { Department: "AL", Money: 100 },
    { Department: "OB", Money: 200 }
];

var holder = {};

awards.forEach(function(award) {
  if (holder.hasOwnProperty(award.Department)) {
    holder[award.Department] = holder[award.Department] + award.Money;
  } else {
    holder[award.Department] = award.Money;
  }
});

var finalArray = [];

for (var prop in holder) {
    finalArray.push( {[prop]: holder[prop]} );
}

console.log(finalArray);

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