Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda