Im experimenting with the espn public API and am trying to use their json to access NFL player information.
the json im accessing succesfully looks like:
{
"sports": [
{
"name": "football",
"id": 20,
"leagues": [
{
"name": "National Football League",
"abbreviation": "nfl",
"id": 28,
"groupId": 9,
"shortName": "NFL",
"athletes": [
{
"id": 14466,
"firstName": "Isa",
"lastName": "Abdul-Quddus",
"fullName": "Isa Abdul-Quddus",
"displayName": "Isa Abdul-Quddus",
"shortName": "I. Abdul-Quddus",
"links": {
"api": {
"athletes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/14466"
},
"news": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/14466/news"
},
"notes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/14466/news/notes"
}
},
"web": {
"athletes": {
"href": "http://espn.go.com/nfl/player/_/id/14466/isa-abdul-quddus?ex_cid=espnapi_public"
}
},
"mobile": {
"athletes": {
"href": "http://m.espn.go.com/nfl/playercard?playerId=14466&ex_cid=espnapi_public"
}
}
}
},
{
"id": 8645,
"firstName": "Hamza",
"lastName": "Abdullah",
"fullName": "Hamza Abdullah",
"displayName": "Hamza Abdullah",
"shortName": "H. Abdullah",
"links": {
"api": {
"athletes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/8645"
},
"news": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/8645/news"
},
"notes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/8645/news/notes"
}
},
"web": {
"athletes": {
"href": "http://espn.go.com/nfl/player/_/id/8645/hamza-abdullah?ex_cid=espnapi_public"
}
},
"mobile": {
"athletes": {
"href": "http://m.espn.go.com/nfl/playercard?playerId=8645&ex_cid=espnapi_public"
}
}
}
},
{
"id": 11910,
"firstName": "Husain",
"lastName": "Abdullah",
"fullName": "Husain Abdullah",
"displayName": "Husain Abdullah",
"shortName": "H. Abdullah",
"links": {
"api": {
"athletes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/11910"
},
"news": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/11910/news"
},
"notes": {
"href": "http://api.espn.com/v1/sports/football/nfl/athletes/11910/news/notes"
}
} ........
]
}
]
}
],
"resultsOffset": 0,
"resultsLimit": 50,
"resultsCount": 3301,
"timestamp": "2013-01-06T19:30:17Z",
"status": "success"
}
and heres the html / javascript Im using:
$(document).ready(function(){
$.getJSON("http://api.espn.com/v1/sports/football/nfl/athletes?apikey=MY-API-KEY-HERE&_accept=application/json",
function(data){
$.each(data["sports"], function(i,item){
$("#infoDiv").append( [i] + " - " + item.name + "<br>" );
});
});
});
i can get this to display 0 - football but cant use something like
$.each(data["sports"]["leagues"]["athletes"], function(i,item){
$("#infoDiv").append( [i] + " - " + item.firstName + "<br>" );
to access the individual athlete data such as item.firstName , etc.
i keep getting the following error:
TypeError: data.sports.leagues is undefined
what am I missing? I'm using this same code structure successfully with a couple of other API's that provide json. the ESPN json is a little more complex in comparison though.
thanks for any light you can shed on this for me.
sports, leagues and athletes are arrays, for example: sports[0] is an object (the one with name='football')
You should iterate each like this (not tested):
$.each(data.sports, function(i,sport) {
$.each(sport.leagues, function(i,league) {
$.each(league.athletes, function(i,athlete) {
$("#infoDiv").append( [i] + " - " + athlete.firstName + "<br>" );
});
});
});
sports, leagues and athletes are arrays which you need to iterate.
for (var i=0; i<data.sports.length; i++) {
var sport = data.sports[i];
$("#infoDiv").append( [i] + " - " + sport.name + "<br>" );
for (var j=0; j<sport.leagues.length; j++) {
var league = sport.leagues[j];
$("#infoDiv").append( [i,j] + " - " + league.name + "<br>" );
for (var k=0; k<league.athletes.length; k++) {
var athlete = league.athletes[k];
$("#infoDiv").append( [i,j,k] + " - " + athlete.fullName + "<br>" );
}
}
}
Related
I am a noob so please forgive me. I have the following JSON file:
`{ "Series": {"Next":
[ { "Name": "Cheese", "Price" : 2.50, "Location": "Refrigerated foods"},
{ "Name": "Crisps", "Price" : 3, "Location": "the Snack isle"},
{ "Name": "Pizza", "Price" : 4, "Location": "Refrigerated foods"},
{ "Name": "Chocolate", "Price" : 1.50, "Location": "the Snack isle"},
{ "Name": "Self-raising flour", "Price" : 1.50, "Location": "Home baking"},
{ "Name": "Ground almonds", "Price" : 3, "Location": "Home baking"} ]}`
I'm trying to reference the Name, Location and Price but it's now working. Here is the JavaScript code I am using:
.then(function(json) {
for(var i = 0; i < json.Next.length; i++) {
var listItem = document.createElement('li_prod');
listItem.innerHTML = '<strong_prod>' + json.Next[i].Name + '</strong_prod>';
listItem.innerHTML +=' can be found in ' + json.Next[i].Location + '.';
listItem.innerHTML +=' Cost: <strong_prod>£' + json.Next[i].Price + '</strong_prod>';
myList.appendChild(listItem);
}
that code is not picking up the Name, Location or price. How can I reference the data? Something like json.Series.Next[i].Name?
with the structure of your object it's more json.Series.Next instead of json.Next
var json = {
"Series": {
"Next":
[{
"Name": "Cheese",
"Price": 2.50,
"Location": "Refrigerated foods"
},
{
"Name": "Crisps",
"Price": 3,
"Location": "the Snack isle"
},
{
"Name": "Pizza",
"Price": 4,
"Location": "Refrigerated foods"
},
{
"Name": "Chocolate",
"Price": 1.50,
"Location": "the Snack isle"
},
{
"Name": "Self-raising flour",
"Price": 1.50,
"Location": "Home baking"
},
{
"Name": "Ground almonds",
"Price": 3,
"Location": "Home baking"
}
]
}
}
var myList = document.getElementById('my-list');
for (var i = 0; i < json.Series.Next.length; i++) {
var listItem = document.createElement('li_prod');
listItem.innerHTML = '<strong_prod>' + json.Series.Next[i].Name + '</strong_prod>';
listItem.innerHTML += ' can be found in ' + json.Series.Next[i].Location + '.';
listItem.innerHTML += ' Cost: <strong_prod>£' + json.Series.Next[i].Price + '</strong_prod>';
myList.appendChild(listItem);
}
<div id="my-list">
</div>
I'm trying to create a JSON object for an API call which has the following format:
....
"Key": "Value",
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "20",
"Width": "25",
"Height": "30"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "80"
}
},
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "15",
"Width": "24",
"Height": "27"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "50"
}
},
"Key": "Value",
....
I should add as many "Package" objects as needed. However, I've tried doing this in many different ways but every time that I parse the variable to be used the first objects get overwritten and I end up with only the last object.
This is what I'm trying at the moment, still with no luck:
var lineItems = '{';
for (var i=0;i<inputObject.packages.length;i++) {
lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
if (i !== inputObject.packages.length-1) {
lineItems += ',';
}
}
lineItems += '}';
lineItems = JSON.parse(lineItems);
How about numbering your packages, ie:
for (var i=0;i<inputObject.packages.length;i++) {
lineItems+='"Package" + i : { ... }'
}
edit: to get required result (as an array - because it's not JSON), here's an example:
var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);
I have a problem with the correct converting array to the form what I need from a graph plugin. I have a JSON which looks like below, from this file I have to count how many titles I have (see pic. 1). Hope you will understand from the pictures.
[
{
"name": "Mike Frost",
"title": "value_1",
"gender": "Male"
},
{
"name": "Hans Karl",
"title": "value_6",
"gender": "Male"
},
{
"name": "Kelly Clarkson",
"title": "value_3",
"gender": "Female"
},
...
]
This what I've got so far:
This what I need:
There is my script which counts values from JSON.
var employeeData = require('json!../path/to/json.json');
var obj = [];
for (var i = 0, j = employeeData.length; i < j; i++) {
if (obj[employeeData[i]['title']]) {
obj[employeeData[i]['title']]++;
}
else {
obj[employeeData[i]['title']] = 1;
}
}
One convenient way to do this is with a map (either a real Map if you're using ES2015, or an object we're using as a map if you're using ES5 or earlier). You build a new array and also keep track of the array entries in the map keyed by the value_X value:
var json = '[' +
' {' +
' "name": "Mike Frost",' +
' "title": "value_1",' +
' "gender": "Male"' +
' },' +
' {' +
' "name": "Hans Karl",' +
' "title": "value_6",' +
' "gender": "Male"' +
' },' +
' {' +
' "name": "Another Six",' +
' "title": "value_6",' +
' "gender": "Male"' +
' },' +
' {' +
' "name": "Kelly Clarkson",' +
' "title": "value_3",' +
' "gender": "Female"' +
' },' +
' {' +
' "name": "Another 3",' +
' "title": "value_3",' +
' "gender": "Female"' +
' },' +
' {' +
' "name": "Yet Another 3",' +
' "title": "value_3",' +
' "gender": "Female"' +
' }' +
']';
// Parse the JSON
var data = JSON.parse(json);
// The new array we'll build
var newArray = [];
// Our "map"
var map = Object.create(null);
// Loop the parsed data
data.forEach(function(entry) {
// Get the existing new entry if any
var mapEntry = map[entry.title];
if (mapEntry) {
// We have one, increase its `value`
++mapEntry.value;
} else {
// There isn't one, create it with a count of 1
// and save it to the array
mapEntry = map[entry.title] = {
label: entry.title,
value: 1
};
newArray.push(mapEntry);
}
});
// Done
console.log(newArray);
That can be written much more concisely, but I wanted to call out the individual parts of what I was doing.
In ES2015+:
const json = `[
{
"name": "Mike Frost",
"title": "value_1",
"gender": "Male"
},
{
"name": "Hans Karl",
"title": "value_6",
"gender": "Male"
},
{
"name": "Another Six",
"title": "value_6",
"gender": "Male"
},
{
"name": "Kelly Clarkson",
"title": "value_3",
"gender": "Female"
},
{
"name": "Another 3",
"title": "value_3",
"gender": "Female"
},
{
"name": "Yet Another 3",
"title": "value_3",
"gender": "Female"
}
]`;
// Parse the JSON
const data = JSON.parse(json);
// The new array we'll build
const newArray = [];
// Our map
const map = new Map();
// Loop the parsed data
data.forEach(entry => {
// Get the existing new entry if any
let mapEntry = map.get(entry.title);
if (mapEntry) {
// We have one, increase its `value`
++mapEntry.value;
} else {
// There isn't one, create it with a count of 1
// and save it to the array
mapEntry = {
label: entry.title,
value: 1
};
map.set(entry.title, mapEntry);
newArray.push(mapEntry);
}
});
// Done
console.log(newArray);
You can use Array.prototype.reduce and a hash table to group the data - see demo below:
var object=[{name:"Mike Frost",title:"value_1",gender:"Male"},{name:"Hans Karl",title:"value_6",gender:"Male"},{name:"Kelly Clarkson",title:"value_3",gender:"Female"},{name:"Mike Frost",title:"value_1",gender:"Male"},{name:"Hans Karl",title:"value_6",gender:"Male"}];
var result = object.reduce(function(hash){
return function(prev, curr){
if(hash[curr.title])
hash[curr.title].value++;
else {
hash[curr.title] = {label: curr.title, value: 1};
prev.push(hash[curr.title]);
}
return prev;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
You could iterate the array and count the occurence of the same titles.
var data = [{ "name": "Mike Frost", "title": "value_1", "gender": "Male" }, { "name": "Hans Karl", "title": "value_6", "gender": "Male" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, ],
result = data.reduce(function (hash) {
return function (r, a) {
if (!hash[a.title]) {
hash[a.title] = { label: a.title, value: 0 };
r.push(hash[a.title]);
}
hash[a.title].value++;
return r;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6 with Map
var data = [{ "name": "Mike Frost", "title": "value_1", "gender": "Male" }, { "name": "Hans Karl", "title": "value_6", "gender": "Male" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, { "name": "Kelly Clarkson", "title": "value_3", "gender": "Female" }, ],
result = data.reduce(
(map =>
(r, a) =>
(!map.has(a.title) && map.set(a.title, r[r.push({ label: a.title, value: 0 }) - 1]), map.get(a.title).value++, r)
)(new Map), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
Guys
I want to read from json file ,i create json file and use ajax to read from it.
i create Video object which contain Courses objects (title & URL)
.
i try to read title & url of HTML as Example but no data show in the HTML page .
{
"video": {
"HTML": [
{
"title": "HTML Intro",
"URL": "http://www.youtube.com/embed/dD2EISBDjWM"
},
{
"title": "Lists",
"URL": "http://www.youtube.com/embed/09oErCBjVns"
},
{
"title": "Tables",
"URL": "http://www.youtube.com/embed/wvR40su_XBM"
},
{
"title": "Links",
"URL": "http://www.youtube.com/embed/U4UHoiK6Oo4"
},
{
"title": "Images",
"URL": "http://www.youtube.com/embed/Zy4KJeVN7Gk"
}
],
"CSS": [
{
"title": "Applying Styles",
"URL": "http://www.youtube.com/embed/Wz2klMXDqF4"
},
{
"title": "Selectors",
"URL": "http://www.youtube.com/embed/6rKan6loNTw"
},
{
"title": "Box Model",
"URL": "http://www.youtube.com/embed/NR4arpSA2jI"
},
{
"title": "Positioning",
"URL": "http://www.youtube.com/embed/W5ycN9jBuBw"
}
],
"JavaScript": [
{
"title": "Introduction to JavaScript",
"URL": "http://www.youtube.com/embed/yQaAGmHNn9s"
},
{
"title": "Comments and Statements",
"URL": "http://www.youtube.com/embed/yUyJ1gcaraM"
},
{
"title": "Variables",
"URL": "http://www.youtube.com/embed/og4Zku5VVl0"
},
{
"title": "Functions",
"URL": "http://www.youtube.com/embed/5nuqALOHN1M"
},
{
"title": "Conditions",
"URL": "http://www.youtube.com/embed/5gjr15aWp24"
},
{
"title": "Objects",
"URL": "http://www.youtube.com/embed/mgwiCUpuCxA"
},
{
"title": "Arrays",
"URL": "http://www.youtube.com/embed/nEvBcwlpkBQ"
}
],
"Jquery": [
{
"title": "Introduction",
"URL": "http://www.youtube.com/embed/hMxGhHNOkCU"
},
{
"title": "Event Binding",
"URL": "http://www.youtube.com/embed/G-POtu9J-m4"
},
{
"title": "DOM Accessing",
"URL": "http://www.youtube.com/embed/LYKRkHSLE2E"
},
{
"title": "Image Slider",
"URL": "http://www.youtube.com/embed/KkzVFB3Ba_o"
}
]
}
}
i use ajax to read from it , i need to read all HTML titles and URLs . what is the wrong with this ?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="id01"></div>
<script>
var xhr;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('GET', 'video.json');
xhr.onreadystatechange = function ()
{
if ((xhr.readyState === 4) && (xhr.status === 200)) {
var arr = JSON.parse(xhr.responseText);
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
video[HTML][i].title +
"</td><td>" +
video[HTML][i].URL +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
}
xhr.send();
</script>
</body>
</html>
Try substituting video["HTML"][i].title where "HTML" is string for HTML at video[HTML][i].title , also arr is not an array, but an object
var out = "<table>";
for (var i = 0; i < json.video["HTML"].length; i++) {
out += "<tr><td>" +
json.video["HTML"][i].title +
"</td><td>" +
json.video["HTML"][i].URL +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
var json = {
"video": {
"HTML": [{
"title": "HTML Intro",
"URL": "http://www.youtube.com/embed/dD2EISBDjWM"
}, {
"title": "Lists",
"URL": "http://www.youtube.com/embed/09oErCBjVns"
}, {
"title": "Tables",
"URL": "http://www.youtube.com/embed/wvR40su_XBM"
}, {
"title": "Links",
"URL": "http://www.youtube.com/embed/U4UHoiK6Oo4"
},
{
"title": "Images",
"URL": "http://www.youtube.com/embed/Zy4KJeVN7Gk"
}
],
"CSS": [{
"title": "Applying Styles",
"URL": "http://www.youtube.com/embed/Wz2klMXDqF4"
}, {
"title": "Selectors",
"URL": "http://www.youtube.com/embed/6rKan6loNTw"
}, {
"title": "Box Model",
"URL": "http://www.youtube.com/embed/NR4arpSA2jI"
}, {
"title": "Positioning",
"URL": "http://www.youtube.com/embed/W5ycN9jBuBw"
}],
"JavaScript": [{
"title": "Introduction to JavaScript",
"URL": "http://www.youtube.com/embed/yQaAGmHNn9s"
}, {
"title": "Comments and Statements",
"URL": "http://www.youtube.com/embed/yUyJ1gcaraM"
}, {
"title": "Variables",
"URL": "http://www.youtube.com/embed/og4Zku5VVl0"
}, {
"title": "Functions",
"URL": "http://www.youtube.com/embed/5nuqALOHN1M"
}, {
"title": "Conditions",
"URL": "http://www.youtube.com/embed/5gjr15aWp24"
}, {
"title": "Objects",
"URL": "http://www.youtube.com/embed/mgwiCUpuCxA"
}, {
"title": "Arrays",
"URL": "http://www.youtube.com/embed/nEvBcwlpkBQ"
}],
"Jquery": [{
"title": "Introduction",
"URL": "http://www.youtube.com/embed/hMxGhHNOkCU"
}, {
"title": "Event Binding",
"URL": "http://www.youtube.com/embed/G-POtu9J-m4"
}, {
"title": "DOM Accessing",
"URL": "http://www.youtube.com/embed/LYKRkHSLE2E"
}, {
"title": "Image Slider",
"URL": "http://www.youtube.com/embed/KkzVFB3Ba_o"
}]
}
};
var out = "<table>";
for (var i = 0; i < json.video["HTML"].length; i++) {
out += "<tr><td>" +
json.video["HTML"][i].title +
"</td><td>" +
json.video["HTML"][i].URL +
"</td></tr>";
}
out += "</table>";
document.body.innerHTML = out;
This
video[HTML][i].title
Should be
video.html[i].title
I'm using the foursquare venues API to populate a select menu and list in my web app. I'd like to sort the venues alphabetically by name.
Here is a JSON response from the foursquare API, which has some venues:
[ { "reasons": { "count": 1, "items": [ { "summary": "This spot is popular on foursquare", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": { "id": "4c6ee03fb5a5236a74744b52", "name": "Peninsular Paper Dam", "contact": {}, "location": { "address": "1265 Leforge Rd", "crossStreet": "at Huron River Rd", "lat": 42.256628, "lng": -83.623933, "distance": 892, "postalCode": "48198", "city": "Ypsilanti", "state": "MI", "country": "United States", "cc": "US" }, "categories": [ { "id": "4bf58dd8d48988d165941735", "name": "Scenic Lookout", "pluralName": "Scenic Lookouts", "shortName": "Scenic Lookout", "icon": { "prefix": "https://foursquare.com/img/categories_v2/parks_outdoors/sceniclookout_", "suffix": ".png" }, "primary": true } ], "verified": false, "stats": { "checkinsCount": 31, "usersCount": 12, "tipCount": 0 }, "likes": { "count": 0, "groups": [] }, "specials": { "count": 0, "items": [] }, "photos": { "count": 2, "groups": [] } } }, { "reasons": { "count": 1, "items": [ { "summary": "This spot is popular on foursquare", "type": "general", "reasonName": "globalInteractionReason" } ] }, "venue": { "id": "4ba58202f964a520cb0d39e3", "name": "Benito's Pizza", "contact": { "phone": "7349610707", "formattedPhone": "(734) 961-0707" }, "location": { "address": "1088 N Huron River Dr", "lat": 42.256532, "lng": -83.629082, "distance": 1035, "postalCode": "48197", "city": "Ypsilanti", "state": "MI", "country": "United States", "cc": "US" }, "categories": [ { "id": "4bf58dd8d48988d1ca941735", "name": "Pizza Place", "pluralName": "Pizza Places", "shortName": "Pizza", "icon": { "prefix": "https://foursquare.com/img/categories_v2/food/pizza_", "suffix": ".png" }, "primary": true } ], "verified": false, "stats": { "checkinsCount": 50, "usersCount": 34, "tipCount": 0 }, "url": "http://www.benitospizza.com/", "likes": { "count": 0, "groups": [] }, "menu": { "type": "foodAndBeverage", "url": "https://foursquare.com/v/benitos-pizza/4ba58202f964a520cb0d39e3/menu", "mobileUrl": "https://foursquare.com/v/4ba58202f964a520cb0d39e3/device_menu" }, "specials": { "count": 0, "items": [] }, "photos": { "count": 0, "groups": [] } } } ]
I'm able to parse this response with this code:
for (var i = 0; i < venues.length; i++) {
name = venues[i]['venue']['name'];
category = venues[i]['venue']['categories'][0]['name'];
icon = venues[i]['venue']['categories'][0]['icon']['prefix'];
icon = icon.slice(0, -1); // remove trailing "_" character
icon = icon + venues[i]['venue']['categories'][0]['icon']['suffix'];
address = venues[i]['venue']['location']['address'];
city = venues[i]['venue']['location']['city'];
state = venues[i]['venue']['location']['state'];
distance_meters = venues[i]['venue']['location']['distance'];
distance_miles = distance_meters / 1609.34;
distance_miles = Math.round(distance_miles*100)/100;
x = 1; // in the product use i for index below
HTMLmarkupList += "<li><img src=\"" + icon + "\" class=\"ui-li-thumb\" style=\"margin: 23px 10px\" onerror=\"ImgError(this);\">" + "<h3 style=\"margin-left: -40px\">" + name + "</h3><p style=\"margin-left: -40px\">" + category + "</p><p style=\"margin-left: -40px\">" + address + ", " + city + ", " + state + "</p><p style=\"margin-left: -40px\">" + distance_miles + " miles from you.</p></li>";
HTMLmarkupSelect += "<option value\"" + i + "\">" + name + "</option>";
}
Right now, the value of the select is just i, but as I'll be needing to store other variables along with the name in my database I may update the value in each select option to include things like the address, city, state, etc.... I mention this because if I was only using the name in the select, I could just build an array of names and use the javascript sort method.
Can anyone help with how to sort the venues alphabetically by name? Thanks.
Information:
http://www.w3schools.com/jsref/jsref_sort.asp
Example:
venues.sort(function(a,b){
if(a.venue.name == b.venue.name) return 0;
return (a.venue.name < b.venue.name) ? -1 : 1;
});