Thassa
Thassa

Reputation: 542

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.

Upvotes: 0

Views: 1691

Answers (3)

Fabio Beltramini
Fabio Beltramini

Reputation: 2511

You might also look into the native array map method, which saves you having to create an array and then push things onto it. It just returns a new array given the original array by applying the mapping function on each item.

$.getJSON("planes.json",function(data){
    console.log(data.map(function(plane){return plane.id;}))
}

However, this is not available in IE<=8 if I recall correctly.

Upvotes: 0

Zeeshan
Zeeshan

Reputation: 619

Please check following solution. I have hard coded plane data instead of getting from file but solution is same. You just need update your $.each line by iterating over data instead of data.id (this is you'r bug rest of code is fine).

var data = [{
  "id": "Ravnica"
}, {
  "id": "Lorwyn"
}, {
  "id": "Innistrad"
}, {
  "id": "Zendikar"
}, {
  "id": "Kamigawa"
}, {
  "id": "Mirrodin"
}, {
  "id": "Shandalar"
}, {
  "id": "Alara"
}, {
  "id": "Fiora"
}];
var planes = [];
//surround this each with your $.getJSON. I have just hardcoded json data instead of getting it from file
$.each(data, function(index, val) {
  planes.push(val.id);
});

console.log(planes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Your update plunker link Plunker

Upvotes: 0

bitten
bitten

Reputation: 2543

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.

Upvotes: 1

Related Questions