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!
This question is related to
javascript
jquery
for-loop
iteration
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");});
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);
});
Late, but can be done by using Object.keys like,
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
Source: Stackoverflow.com