I have the following code which works fine:-
$.getJSON("shipping.json")
.done(function(data) {
getUniqueCountries = function() {
var countries = [];
$.each(data.Services.intl.en, function( i, item ) {
if (countries.length==0) {
countries += item.countries;
}
else
{
countries += "," + item.countries;
}
});
}
})
However, I would like to make the first part of the $.each dynamic as this could be one of 3 possibilities based on a predefined variable, e.g.
var foo = "intl"
so the new line would read:-
$.each(data.Services.foo.en, function( i, item )
I can add another line of code and use an eval which works fine, but understand that this is not seen as best practice. i.e.
var foo = "intl";
var bar = eval("data.Services." + foo + ".en");
$.each(bar, function( i, item )
I have tried using JSON.parse (as seems to be popular way to resolve on google) instead of eval, i.e.
var bar = JSON.parse("data.Services." + foo + ".en");
but get an error :
'Unexpected token d'.
A snippet of the JSON file if needed :-
{
"Services": {
"intl": {
"en": [
{
"service": "PREMIER",
"countries": "United Kingdom",
"date": "Thursday 24th 10:00"
}
]
}
}
}
So I would like to know how to pass the variable foo into JavaScript to get the correct data and not get an error, without using the Eval function, or am I good to use the Eval function after all?
Thanks in advance for any help