Group an array of objects

Asked

Viewed 1,235 times

0

I am trying to group an array of objects that comes from the database in the following format:

[
       {
          '12312312': { 'first_name': 'David', 'id_question': 0, 'acertou': 1 },
          '23423423': { 'first_name': 'Luis', 'id_question': 0, 'acertou': 1 },
          '45645645': { 'first_name': 'José', 'id_question': 0, 'acertou': 1 }
       },
       {
          '12312312': { 'first_name': 'David', 'id_question': 1, 'acertou': 1 },
          '23423423': { 'first_name': 'Luis', 'id_question': 1, 'acertou': 0 },
          '45645645': { 'first_name': 'José', 'id_question': 1, 'acertou': 1 }
       },
       {
          '12312312': { 'first_name': 'David', 'id_question': 2, 'acertou': 1 },
          '23423423': { 'first_name': 'Luis', 'id_question': 2, 'acertou': 1 },
          '45645645': { 'first_name': 'José', 'id_question': 2, 'acertou': 0 }
       }
]

I need to transform it to the following format:

[
    {
        first_name: "David",
        resultados: [
            { "id_question": 0, "acertou": 1 },
            { "id_question": 1, "acertou": 1 },
            { "id_question": 2, "acertou": 1 }
        ]
     },
     {
         first_name: "Luis",
         resultados: [
            { "id_question": 0, "acertou": 1 },
            { "id_question": 1, "acertou": 0 },
            { "id_question": 2, "acertou": 1 }
         ]
     },
     {
          first_name: "José",
          resultados: [
            { "id_question": 0, "acertou": 1 },
            { "id_question": 1, "acertou": 1 },
            { "id_question": 2, "acertou": 0 }
          ]
     }
]

Could someone please help me?

Thank you.

3 answers

0

Dude, I don’t even think you need to create another array, use . foreach or . indexof and good. For example:

var arrTemp = JSON.parse(resposta_do_banco);
arrTemp.forEach(fillResumeArr);

function fillResumeArr(item, index)
{
    //como seus subitens são arrays, verifico se o item é um array, e boa
    if(item.isarray()){
        //faz o que quiser com o item.
    }
}
  • It is that I need to leave in that format to facilitate the work on the front.

0

I solved as follows using the lodash groupBy:

        let itt = []; // Recebe os valores do banco de dados             
        let arr1 = [];

         for (let i = 0; i < itt.length; i++) {
            arr1.push(Object.values(itt[i]))
         }

         let arr2 = [];

         for (let j = 0; j < arr1.length; j++) {
            for (let z = 0; z < Object.values(arr1[j]).length; z++) {
               arr2.push(arr1[j][z])
            }
         }

         let arr3 = _.groupBy(arr2, 'first_name')

         let arr = []

         Object.keys(arr3).map(function (objectKey, index) {
            let value = arr3[objectKey];
            let val1 = {
               first_name: objectKey,
               respostas: value
            }
            arr.push(val1)
         });

         this.itemsFiltered = arr; // Valores no formato que desejo enviar para o front

It worked for me.

  • if it worked for you should mark your answer as correct, to facilitate the life of those who have a similar problem and end up falling in your question

0

Opa, I managed to get your expected result using only pure Javascript.

Follows code below:

var arrBase = [
  {
    12312312: { first_name: "David", id_question: 0, acertou: 1 },
    23423423: { first_name: "Luis", id_question: 0, acertou: 1 },
    45645645: { first_name: "José", id_question: 0, acertou: 1 },
  },
  {
    12312312: { first_name: "David", id_question: 1, acertou: 1 },
    23423423: { first_name: "Luis", id_question: 1, acertou: 0 },
    45645645: { first_name: "José", id_question: 1, acertou: 1 },
  },
  {
    12312312: { first_name: "David", id_question: 2, acertou: 1 },
    23423423: { first_name: "Luis", id_question: 2, acertou: 1 },
    45645645: { first_name: "José", id_question: 2, acertou: 0 },
  },
];

var arrFinal = [];

// loop através da lista base
for (let idx = 0; idx  e.first_name === elementoBase.first_name
    );

    // primeira situação: se existir o elemento devo acrescentar o resultado
    if (elementoEncontrado) {
      // encontro o index do elemento para substituí-lo posteriormente
      const idxElementoEncontrado = arrFinal.findIndex(
        (e2) => e2.first_name === elementoEncontrado.first_name
      );
      // substituo o elemento acrescentando o resultado
      arrFinal[idxElementoEncontrado] = {
        first_name: elementoBase.first_name,
        resultados: elementoEncontrado.resultados.concat({
          id_question: elementoBase.id_question,
          acertou: elementoBase.acertou,
        }),
      };
      // segunda situação: se não existir o elemento
      // devo criar um array novo com primeiro resultado
    } else {
      arrFinal.push({
        first_name: elementoBase.first_name,
        resultados: [
          {
            id_question: elementoBase.id_question,
            acertou: elementoBase.acertou,
          },
        ],
      });
    }
  }
}

console.log(JSON.stringify(arrFinal, null, "\t"));

// [
//     {
//         'first_name': 'David',
//         'resultados': [
//             {
//                 'id_question': 0,
//                 'acertou': 1
//             },
//             {
//                 'id_question': 1,
//                 'acertou': 1
//             },
//             {
//                 'id_question': 2,
//                 'acertou': 1
//             }
//         ]
//     },
//     {
//         'first_name': 'Luis',
//         'resultados': [
//             {
//                 'id_question': 0,
//                 'acertou': 1
//             },
//             {
//                 'id_question': 1,
//                 'acertou': 0
//             },
//             {
//                 'id_question': 2,
//                 'acertou': 1
//             }
//         ]
//     },
//     {
//         'first_name': 'José',
//         'resultados': [
//             {
//                 'id_question': 0,
//                 'acertou': 1
//             },
//             {
//                 'id_question': 1,
//                 'acertou': 1
//             },
//             {
//                 'id_question': 2,
//                 'acertou': 0
//             }
//         ]
//     }
// ]

Codepen: https://codepen.io/maicongodinho1/pen/wvdpXpj

Any questions just ask.

Browser other questions tagged

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