I have the following code:
$.getJSON('data.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<option id="' + key + '">' + val + '</option>');
});
$('<select/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This works fine for a simple JSON file but I’ve got a bit more complicated data (this is how it’s been given to me):
{
"Shares": [
{
"shareName": "Frontier",
"shareID": "FML"
},
{
"shareName": "Global Petroleum",
"shareID": "GBP"
},
{
"shareName": "Tower Petroleum",
"shareID": "TRP"
},
{
"shareName": "Aquarius Platinum",
"shareID": "AQP"
}
]
}
This simply populates a drop down menu, how should I modify the syntax so it reads the “ShareName” for each within Shares?
Thanks!
Thanks everyone for the answers, I can only choose one so chose the first reply, but I really appreciate everybody’s input!
Firstly, you’ll have to iterate over
data.Sharesinstead. Note the capitalS; JavaScript is case sensitive.You’ll also have to reference the
shareNameandshareIDattributes rather than simply the key and value.To cement the understanding, what you have is an object (
data) which has an attribute (Shares) which is an array of objects. Each object in that array has 2 attributes;shareIDandshareName.