Thassa Thassa - 1 year ago 66
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

function. What I want to do is pull the "id" section of a JSON file and push it into an array called
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(, function (index, val) {
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"}


Any help is much appreciated.

Answer Source

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

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

    "id": [

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