0

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

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

2 Answers2

1

If i'm understanding correctly, you should be able to do the following:

$.each(data.Services[foo].en, function( i, item ) {
        if (countries.length==0) {
            countries += item.countries;
        }
        else
        {
            countries += "," + item.countries;
        }
    });

Properties in javascript objects can be accessed as if you are accessing a particular key inside an array. For example you can do window.location or window["location"]

Hope this helps

Mark Camilleri
  • 130
  • 2
  • 11
  • Thanks, this has resolve the issue. I did try [foo] before as research had pointed me to it, but I including the . before i.e. Services.[foo] instead of Services[foo] and was getting an error 'Unexpected token ['. Thanks again for the prompt reply. Also to Madara below, who posted the same answer but a minute later. – user2215975 Nov 26 '15 at 12:30
0

It's actually fairly simple. JavaScript supports dynamic object keys with the [] notation:

data.Services[foo].en // Where foo = 'intl' or something.
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • Thanks for the prompt response Madara. Had tried this before, but had the syntax slightly wrong (please see above). Thanks again. – user2215975 Nov 26 '15 at 12:34