2

My object is as below

var masterData = {      
    "region":[
            {"key":"1","value":"AMS"},
            {"key":"2","value":"APJ"},
            {"key":"3","value":"EMEA"}
    ]
};

var key = 'region';
var strList = 'masterData.'+key;

$.each($(strList), function(i, row) {
    alert(row.key); 
});

It's not entering the loop, but if I replace the variable with the actual object, it works. For example:

$.each($(masterData.region), function(i, row) {
    alert(row.key);     
});

I want to do the same via a variable, like the first one. What am I missing here?

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
user1447718
  • 641
  • 1
  • 9
  • 22
  • This is **not** JSON. This is an object literal. Unfortunately many people make the mistake to confuse object literals with JSON. See [There is no such thing as a "JSON object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). – Felix Kling Aug 02 '13 at 15:47

2 Answers2

4

Since an object is considered an associative array, properties can be accessed by key in this manner:

var key = 'region';
var strList = masterData[key];

Good Overview of Objects as Associative Arrays

Kevin Bowersox
  • 90,944
  • 18
  • 150
  • 184
-1

this worked

    $.each($(eval(strList)), function(i, row) {
    alert(row.key);     
    });
user1447718
  • 641
  • 1
  • 9
  • 22