Iterating a JavaScript object's properties using jQuery

108,021

Solution 1

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

each

Solution 2

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);
});

Solution 3

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");});

Solution 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>
Share:
108,021
tags2k
Author by

tags2k

Scottish C# ASP.NET developer currently living and working in Yorkshire, UK.

Updated on October 16, 2020

Comments

  • tags2k
    tags2k over 3 years

    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!

  • Eugene
    Eugene almost 13 years
    Also I guess, that alerting n isn't intirely correct. At least it could be n.name
  • Tim Büthe
    Tim Büthe almost 13 years
    @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".
  • Eugene
    Eugene almost 13 years
    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. :)
  • andy
    andy over 11 years
    each has got much more features: this is also n. return false breaks the each loop...
  • JustinStolle
    JustinStolle about 9 years
    Using this when a value is null errors with "Uncaught TypeError: Cannot read property 'length' of null"
  • Rick Mac Gillis
    Rick Mac Gillis about 3 years
    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.
  • Tim Büthe
    Tim Büthe about 3 years
    @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.