0

Here is a JSON Array in the URL: http://ins.mtroyal.ca/~nkhemka/2511/process.php

{"Roll":[{"value":3},{"value":5},{"value":2},{"value":6},{"value":2}]}

I am trying to parse this array into a JavaScript array, such as

var diceList = [3, 5, 2, 6, 2 ]

Thus Far I have:

$.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php")
    .done(function (data){
        diceList = $.parseJSON(data);
        alert(diceList);
});

When the code is executed the alert simply says [object Object]. I am unsure of how to accomplish this!

4 Answers 4

3

try map() method to get formatted result, and alert() function can display string value so you can change array into string from join(',') function

$.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php")
    .done(function (data){
        diceList = $.parseJSON(data);
        var list = $.map(diceList.Roll, function(v){
          return v.value;
        })   
        alert(list.join(','));
});
Sign up to request clarification or add additional context in comments.

Comments

0
    $.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php")
    .done(function (data){
        var diceList= new Array(data.Roll.length);
        for( var i= 0; i< data.Roll.length; i++){
            diceList[i]=data.Roll[i].value;
        }
        alert(diceList);
    });

Comments

0

Iterate Roll items to put their values into an array.

JsFiddle

$.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php")
    .done(function (data) {
        var diceList = $.parseJSON(data);
        var array = [];

        $.each( diceList.Roll, function(i, item) {

            array.push(item.value);
        });

        alert(array);
});

Comments

0

With underscore it's really easy:

$.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php").done(function (data){
       data = JSON.parse(data); // JSON.parse is the same
       diceList = _.map(data.Roll, function(num){ return num.value; });
       console.log(diceList);
});

Without:

data = JSON.parse(data);
diceList = [];
for (var i in data.Roll)
    diceList.push( data.Roll[i].value );
console.log(diceList);

https://jsfiddle.net/rabztbcd/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.