Group an array of objects



  • I am trying to group an array of objects from the bench 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'm needing to turn it into 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 anyone please help me?

    Thank you.



  • Dude, I don't 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.
    }
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2