How to reference a JavaScript object property with a hyphen in it

Recently, I was playing around with the Milwaukee County Transit System BusTime API when I came across an interesting problem.

 

// Populate a drop-down to select a bus route
function getRoutes(){
var feed = ‘http://realtime.ridemcts.com/bustime/api/v1/getroutes?key=zk6jyqAnqDtzM9fiueVPD2kyd’;

$.getJSON(“https://query.yahooapis.com/v1/public/yql”,
{
format: ‘json’,
q: ‘select * from xml where url=’+'”‘+feed+'”‘
},
function(data) {
console.table(data.query.results.bustime-response.route);
$(‘select[name=routes]’).append(“<option name=””+data.query.results.bustime-response.route.rt+””>”+data.query.results.bustime-response.route.rtnm+”</option>”);
}
);
}
getRoutes();

The object returned has a property with a dash in it.

Dash in a JavaScript object property

 

 

So, how do you deal with it?  There is a way.

// Populate a drop-down to select a bus route
function getRoutes(){
var feed = ‘http://realtime.ridemcts.com/bustime/api/v1/getroutes?key=zk6jyqAnqDtzM9fiueVPD2kyd’;

$.getJSON(“https://query.yahooapis.com/v1/public/yql”,
{
format: ‘json’,
q: ‘select * from xml where url=’+'”‘+feed+'”‘
},
function(data) {
console.table(data.query.results[“bustime-response”].route);
$(‘select[name=routes]’).append(“<option name=””+data.query.results[“bustime-  response”].route.rt+””>”+data.query.results[“bustime-response”].route.rtnm+”</option>”);
}
);
}
getRoutes();

So, you can use a object[“property”] syntax.  Want to see the final product?  You can see it on jsFiddle.

Leave a Reply

Your email address will not be published.