jeudi 20 octobre 2016

selecting a single random object from JSON

I am modifying a jeopardy board and am trying to randomize each of the questions. The items are stored in JSON like so:

[
    {
        "name":"category1",
        "questions":[
            {
                "value":100,
               "question":"Question 1 in category 1 for 100 points test 1",
                "answers":[
                    {
                        "text":"A",
                        "correct":true
                    },
                    {
                        "text":"B",
                        "correct":false
                    },
                    {
                        "text":"C",
                        "correct":false
                    },
                    {
                        "text":"D",
                        "correct":false
                    }
                ]
            }
          ]
      }
]

I will have 3 questions per value level (100).I am trying to pull only one of these values at random to populate on my board, which is done by using this function:

var score = 0;
var map;
function loadBoard(){//function that turns the board.json (loaded in the the map variable) into a jeopardy board
    var board = $('#main-board');
    var columns = map.length;
    var column_width = parseInt(12/columns); //get the width/12 rounded down, to use the bootstrap column width appropriate for the number of categories
        console.log(columns);
        $.each(map, function(i,category){
            //load category name
            var header_class = 'text-center col-md-' + column_width; 
            if (i === 0 && columns % 2 != 0){ //if the number of columns is odd, offset the first one by one to center them

                header_class += ' col-md-offset-1';
            }
            $('.panel-heading').append(
                '<div class="'+header_class+'"><h4>'+category.name+'</h4></div>'
            );
            //add column
            var div_class = 'category col-md-' + column_width;
            if (i === 0 && columns % 2 != 0){
                div_class += ' col-md-offset-1';
            }
            board.append('<div class="'+div_class+'" id="cat-'+i+'" data-category="'+i+'"></div>');
            var column = $('#cat-'+i);

            $.each(category.questions, function(n,question){

      //add questions
                column.append('<div class="well question unanswered" data-question="'+n+'">'+question.value+'</div>')
            });
        });
        $('.panel-heading').append('<div class="clearfix"></div>')

    }

But I can't quite seem to get it to return a single random question in the spot. With using Math.random(); it returns "Undefined." You can check out the project on my Plnkr. Any help on this is greatly appreciated!




Aucun commentaire:

Enregistrer un commentaire