Jquery Object groups with same id

Asked

Viewed 39 times

0

how can I create a group of objects where the id_question 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 equal and would be placed in the same object.

[{id_pergunta: "63", resposta: "não", qtd: "5"},{id_pergunta: "63", resposta:"sim", qtd: "19"}]
  • you have these values in what format? They are in an array and you want to separate in arrays by question? or would you like to map to a different object? type { [id_question] { [answer] [Qtd] }, ... } ??

  • Hello Israel, this in Json format, in case I will popular canvas Graphics and for each group of id_question will be generated a graphic.

  • Carlos Beauty. take a look at the reply I sent, I believe it serves this purpose, since it is grouping the questions and their answers in a structured way.

  • It worked perfectly!! Thank you very much Israel!

1 answer

1


I don’t understand why you want to simply filter objects by question in different arrays. maybe it’s more useful to map to another structure? Here’s 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]);

Browser other questions tagged

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