views:

39

answers:

2

I am working with JSON data with multiple sets of key value pairs - each set constitutes a list. In the simplified example below, The list name is not known beforehand - actually I'll need to populate a select dropdown on the page with the names of each list. How do I retrieve the set names in this situation? Thanks

({
 "list1": 
 [{
     "prodRating": "5",
     "prodReviews": "21"
 },
        {
     "prodRating": "5",
     "prodReviews": "21"
 }],
 "list2": 
 [{
     "prodRating": "5",
     "prodReviews": "21"
 },
        {
     "prodRating": "5",
     "prodReviews": "21"
 }]
})
A: 
var json = ... //something which gets you the json data
for (var listname in json)
    alert(listname)

Would display two alerts in this case saying "list1" and "list2".

Here a little sample page which iterates over an object which is built like yours but the "labels" don't have to be known.

And creates two selects dynamically

http://jsbin.com/azeha

jitter
A: 

JSON key pairs that you show here is like Map with list of JSON object reference by key, "listX". You can iterate them with the key value:

var test = {"list1": 
        [{
            "prodRating": "5",
            "prodReviews": "21"
        },
               {
            "prodRating": "5",
            "prodReviews": "21"
        }],
        "list2": 
        [{
            "prodRating": "5",
            "prodReviews": "21"
        },
               {
            "prodRating": "5",
            "prodReviews": "21"
        }]
       };
    for (var i in test){
     console.log("Key: "+ i); 
     for(var j in test[i]){
      var something = test[i][j]; 
      console.log("Rating: " + something.prodRating + " Reviews: " + something.prodReviews); 
     }
    }

Not sure how you want to layout your drop down. But you can use jquery's html() to generate the html. Hope it helps.

JohnnyBeGood