119

Is there a jQuery way to perform iteration over an object's members, such as in:

    for (var member in obj) {
        ...
    }

I just don't like this for sticking out from amongst my lovely jQuery notation!

tags2k
  • 82,117
  • 31
  • 79
  • 106

4 Answers4

216
$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

ozba
  • 6,522
  • 4
  • 33
  • 40
Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
  • Also I guess, that alerting `n` isn't intirely correct. At least it could be `n.name` – Eugene May 27 '11 at 09:39
  • 2
    @Eugene: I don't get your point. The each function takes an array or object as the first argument and a function as a second. This functions gets calld for every element in the array / every property in the object. Every time the function is called, it get the index and value / name and value passed in as arguments. In my example the parameter "n" are the two string "John" and "JS". The "name" property would be "undefined". – Tim Büthe May 27 '11 at 11:23
  • Yep. I was wrong here. Somehow I thought, that every property in object is another object with for example property name which is a string. Of cource all of that is wrong. So sorry. :) – Eugene May 27 '11 at 15:26
  • 4
    each has got much more features: `this` is also `n`. `return false` breaks the each loop... – andy Sep 05 '12 at 13:04
  • `i` and `n` seriously? Why not `index` and `name` to keep things clean? You did teach me something new though in that `$.each(obj, callback)` doesn't do the same as `$(obj).each(callback)`, so much appreciated. Upvoted. – Rick Mac Gillis Mar 20 '21 at 18:56
  • @RickMacGillis feel free to use whatever variable name you prefer. I would argue that `i` is very common for index in a for each, but you are right `index` and `value` would be a little nicer. – Tim Büthe Mar 22 '21 at 07:53
56

You can use each for objects too and not just for arrays:

var obj = {
    foo: "bar",
    baz: "quux"
};
jQuery.each(obj, function(name, value) {
    alert(name + ": " + value);
});
ozba
  • 6,522
  • 4
  • 33
  • 40
Gumbo
  • 643,351
  • 109
  • 780
  • 844
9

Note: Most modern browsers will now allow you to navigate objects in the developer console. This answer is antiquated.

This method will walk through object properties and write them to the console with increasing indent:

function enumerate(o,s){

    //if s isn't defined, set it to an empty string
    s = typeof s !== 'undefined' ? s : "";

    //if o is null, we need to output and bail
    if(typeof o == "object" && o === null){

       console.log(s+k+": null");

    } else {    

        //iterate across o, passing keys as k and values as v
        $.each(o, function(k,v){

            //if v has nested depth
           if(typeof v == "object" && v !== null){

                //write the key to the console
                console.log(s+k+": ");

                //recursively call enumerate on the nested properties
                enumerate(v,s+"  ");

            } else {

                //log the key & value
                console.log(s+k+": "+String(v));
            }
        });
    }
}

Just pass it the object you want to iterate through:

    var response = $.ajax({
        url: myurl,
        dataType: "json"
    })
    .done(function(a){
       console.log("Returned values:");
       enumerate(a);
    })
    .fail(function(){ console.log("request failed");});
terrabruder
  • 91
  • 2
  • 5
4

Late, but can be done by using Object.keys like,

var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},
  ulkeys=document.getElementById('object-keys'),str='';
var keys = Object.keys(a);
for(i=0,l=keys.length;i<l;i++){
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';
}
ulkeys.innerHTML=str;
<ul id="object-keys"></ul>
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106