Group JSON using javascript reduce()

Asked

Viewed 683 times

3

Is there any way to group a Json using the method Reduce() of Javascript, as shown below:

contas = [{id: 1, descricao: "AGUA", valor: 100, juros: 5},
          {id: 1, descricao: "AGUA", valor: 100, juros: 5},
          {id: 2, descricao: "LUZ", valor: 150, juros: 10},
          {id: 2, descricao: "LUZ", valor: 150, juros: 10}];

returning in the following manner:

contas = [{id:1, descricao: "AGUA", valor: 200, juros: 10},
          {id:2, descricao: "LUZ", valor: 300, juros: 20}];

Any suggestions?

1 answer

3


We can use the reduce starting with an empty array accumulator and adding to the accumulator elements that have the id different. Whenever we find a id equal we add the valor and the juros to what is already there.

Example:

contas = [{id: 1, descricao: "AGUA", valor: 100, juros: 5},
          {id: 1, descricao: "AGUA", valor: 100, juros: 5},
          {id: 2, descricao: "LUZ", valor: 150, juros: 10},
          {id: 2, descricao: "LUZ", valor: 150, juros: 10}];
   
   
var total = contas.reduce(function (acumulador, valor){
  //achar o indice do objeto no acumulador através do id
  var indice = acumulador.map((o) => o.id).indexOf(valor.id); 
  
  if (indice == -1){ //se não existe no acumulador adiciona o objeto corrente
    acumulador.push(valor);
  }
  else { //se já existe aumenta o valor e os juros
    acumulador[indice].valor += valor.valor;
    acumulador[indice].juros += valor.juros;

  }
  
  return acumulador; 

}, []); //iniciar o acumulador com array vazio
          

console.log(total);

  • Perfect! That’s just what I needed, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.