Sumeet Kashyap
Sumeet Kashyap

Reputation: 133

JQuery each on associative JSON object

Hey friends can you help me out with this issue. I have a JSON:

video_orders = {
    "channel": {
        "1": "relevance",
        "2": "published",
        "3": "viewCount",
        "4": "rating"
    },
    "playlist": {
        "1": "position",
        "2": "commentCount",
        "3": "duration",
        "4": "published",
        "5": "title",
        "6": "viewCount"
    },
    "favorites": {
        "1": "standard"
    }
}

What i am trying to do is a Jquery each to get all values inside the keys like "channel", "playlist", "favorites".

Currenly what i am doing is:

$(video_orders['channel']).each(function(index, value){
   console.log(index+' : '+value);
})

So the output should be like:(if i do console.log)

1 : relevance
2 : published
3 : viewCount
4 : rating

But what i get is all wrong. What am i doing wrong? How can accomplish it? Thanks in advance.

Upvotes: 0

Views: 950

Answers (2)

Jordan
Jordan

Reputation: 4628

You're trying to use $(selector).each(function) (which is meant for jQuery selectors) instead of $.each(collection, function) (which is meant for any collection). http://api.jquery.com/jQuery.each/

Upvotes: 0

mu is too short
mu is too short

Reputation: 434985

You're using the wrong each, you want $.each, not $(...).each:

$.each(video_orders['channel'], function(index, value){
   console.log(index+' : '+value);
});

The $(...).each function is used to iterate over a set of matched DOM elements:

Iterate over a jQuery object, executing a function for each matched element.

The $.each function is:

A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.

Demo: http://jsfiddle.net/ambiguous/Ax7Eu/

Upvotes: 4

Related Questions