Create dynamic associative array inside loop

1

I'm having trouble trying to create a dynamic associative array inside a loop, the error returned in the console is Cannot read property 'push' of undefined , the idea is of a sports quiz with 3 questions for each team, I'm using the "data-time" attribute that is equal in the 3 inputs of this team, so when sending the result would be created an array with the name of the team being the key and its "arrays children" would be the answers.

Example of inputs:

<input type="radio" name="respota1" value="respota1" data-time="flamengo">
<input type="radio" name="respota2" value="respota2" data-time="flamengo">
<input type="radio" name="respota3" value="respota3" data-time="flamengo">

Jquery:

var answers = $("input[data-time]:checked");
    var items = new Array();

    $.each( answers, function( key, value ) {

        var time = $(this).attr('data-time');

        switch(time) {

            case 'flamengo':
            items['flamengo'].push($(this).val());
            break;
        }

    });

    console.log(items);

How to proceed?

    
asked by anonymous 03.06.2018 / 07:22

1 answer

2

You are trying to insert something that does not exist in the array:

items['flamengo'] não existe

Another thing is that in this case where more than one item can be marked, it is more appropriate to use checkbox which is suitable for this. The radio should be used only when one of the options is to be chosen.

What you can do is to create a new key this way from the% checked% and go giving checkbox . See that you do not even need to use push :

var answers = $("input[data-time]:checked");
var items = new Array();
var conta = -1;
var flag;

$.each( answers, function( key, value ) {

   var time = $(this).attr('data-time');
   var val  = value.value;

   if(flag != time){
      flag = time;
      var o = {};
      o[time] = [];
      conta++;
      items.push(o);
   }

   items[conta][time].push(val);

});

console.log(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" name="respota1" value="respota1" data-time="flamengo">
<input type="checkbox" checked name="respota2" value="respota2" data-time="flamengo">
<input type="checkbox" name="respota3" value="respota3" data-time="flamengo">

<input type="checkbox" checked name="respota1" value="respota1" data-time="vasco">
<input type="checkbox" name="respota2" value="respota2" data-time="vasco">
<input type="checkbox" checked name="respota3" value="respota3" data-time="vasco">
    
03.06.2018 / 07:43