Jquery Groups of objects with same id

0

How can I create a group of objects where the query_id is equal within a .each $?

Object {id_pergunta: "63", resposta: "não", qtd: "5"}
Object {id_pergunta: "63", resposta: "sim", qtd: "19"}
Object {id_pergunta: "64", resposta: "não", qtd: "19"}
Object {id_pergunta: "65", resposta: "A", qtd: "12"}
Object {id_pergunta: "65", resposta: "B", qtd: "1"}
Object {id_pergunta: "65", resposta: "C", qtd: "2"}
Object {id_pergunta: "65", resposta: "D", qtd: "3"}
Object {id_pergunta: "65", resposta: "E", qtd: "1"}
Object {id_pergunta: "66", resposta: "não", qtd: "11"}
Object {id_pergunta: "66", resposta: "sim", qtd: "8"}

Example: In this case the two id's are the same and would be placed on the same object.

[{id_pergunta: "63", resposta: "não", qtd: "5"},{id_pergunta: "63", resposta:"sim", qtd: "19"}]
    
asked by anonymous 26.02.2018 / 13:40

1 answer

1

I do not understand why you simply want to filter objects by question in different arrays. maybe it is more beneficial to map to another structure? Here is an example that maps to a json:

{
  [nro_pergunta] : {
    [resposta] : [qtd]
  }
}

var respostas = [
  {id_pergunta: "63", resposta: "não", qtd: 5},
  {id_pergunta: "63", resposta: "sim", qtd: 19},
  {id_pergunta: "64", resposta: "não", qtd: 19},
  {id_pergunta: "65", resposta: "A", qtd: 12},
  {id_pergunta: "65", resposta: "B", qtd: 1},
  {id_pergunta: "65", resposta: "C", qtd: 2},
  {id_pergunta: "65", resposta: "D", qtd: 3},
  {id_pergunta: "65", resposta: "E", qtd: 1},
  {id_pergunta: "66", resposta: "não", qtd: 11},
  {id_pergunta: "66", resposta: "sim", qtd: 8}
];

var mapByPergunta = {};

respostas.forEach(r => {
  if(!mapByPergunta.hasOwnProperty(r.id_pergunta)) {
    mapByPergunta[r.id_pergunta] = {};
  }
 
  mapByPergunta[r.id_pergunta][r.resposta] = r.qtd;
});

console.log(mapByPergunta);
console.log(mapByPergunta[63]);
    
26.02.2018 / 14:11