Iterating a JavaScript object's properties usi

2019-01-05 00:53发布

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!

4条回答
The star\"
2楼-- · 2019-01-05 01:31

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 : "";

    //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"){

            //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");});
查看更多
叼着烟拽天下
3楼-- · 2019-01-05 01:45

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);
});
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-05 01:49

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>

查看更多
再贱就再见
5楼-- · 2019-01-05 01:53
$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

查看更多
登录 后发表回答