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
  • 795,719
  • 175
  • 1,089
  • 1,143
user1447718
  • 669
  • 1
  • 11
  • 23
  • 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
  • 93,289
  • 19
  • 159
  • 189
-1

this worked

    $.each($(eval(strList)), function(i, row) {
    alert(row.key);     
    });
user1447718
  • 669
  • 1
  • 11
  • 23