user1184100
user1184100

Reputation: 6894

How to get json object key name from collection and iterate

Below is my json structure. On success of collection.fetch() i'm looping through the structure.

Currently i use

this.collection.each(function(model) { .. }

How do i obtain key name like plants, animals and instead loop using the names.

JSON

var jsonObj = {         // 0 - recommended , 1 - New
   "plants" : [

       {
        "title" : "title1",
            "desc": "description.." 
       },
           {
        "title" : "titl2",
            "desc": "description."  
       }    
    ],
    "animals" : [

       {
        "title" : "title1",
            "desc": "description.." 
       },
           {
        "title" : "titl2",
            "desc": "description."  
       }    
    ]
};

Snapshot of collection

enter image description here

Upvotes: 1

Views: 4233

Answers (2)

dmgig
dmgig

Reputation: 4568

This would work, but you'd use a normal for loop, not "each":

for(i in jsonObj){
     alert(i);
}

here is a fjsfiddle: http://jsfiddle.net/r5nwP/

Is that what you're after?

Upvotes: 3

lucuma
lucuma

Reputation: 18339

You can use the underscore keys to get a list of names:

var thenames =_.keys(yourobject);

In this case thenames will contain a list of the keys you are looking for. Here is the documentation for it:

http://underscorejs.org/#keys

keys_.keys(object) Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3}); => ["one", "two", "three"]

Upvotes: 2

Related Questions