Thassa Thassa - 5 months ago 28
jQuery Question

How can I use jQuery to push JSON data into an array?

I'm new to jQuery, and I'm trying out the

getJSON
function. What I want to do is pull the "id" section of a JSON file and push it into an array called
planes
in jQuery. From there, the array is used in an autocomplete function to fill in the searchable IDs.

var planes = [];
$.getJSON('planes.json', function(data) {
console.log('Filling array...');

//This is where I think the issue is occurring.
//Is using the name of the section you want to use the correct syntax here?
$.each(data.id, function (index, val) {
planes.push(val.id);
console.log('Pushed ' + index);
});
});

// After getJSON, array should look something like this:
// var planes = [
// 'Alara',
// 'Fiora',
// 'Innistrad',
// 'Kamigawa',
// 'Lorwyn',
// 'Mirrodin',
// 'Ravnica',
// 'Shandalar',
// 'Zendikar'
// ];


The JSON file is arranged like so:

[
{"id": "Ravnica"},
{"id": "Lorwyn"},
{"id": "Innistrad"},
{"id": "Zendikar"},
{"id": "Kamigawa"},
{"id": "Mirrodin"},
{"id": "Shandalar"},
{"id": "Alara"},
{"id": "Fiora"}
]


Plunker

Any help is much appreciated.

Answer

You almost have it, although you are looping through data.id which is not what you want to be doing. You should just loop through data, and push val.id.

If you wanted to loop through data.id, then you're json would have to be structured like so:

{
    "id": [
        "things",
        "to",
        "loop",
        "through"
    ]
}

..but it's not, so just loop through data.