简体   繁体   中英

jQuery iterating over an Object(JSON)

The JSON is:

{"Name":"bb", "age":"10"}

I searched a lot of in the Internet but most of the answers are for I know "Name" and "age" previously, so they reference like j.Name, j.age.

I am just wanting to do equivalent thing as, we don't know the keys inside the object, we want to iterate over all items and print out both KEY and VALUE(we don't know KEY previously). The for each statement is doing fine in Firefox but I found IE can't support for each loop...

You can use a for...in loop, like this:

var obj = {"Name":"bb", "age":"10"};
for(var key in obj) {
  if(obj.hasOwnProperty(key))
    alert("Key: " + key + "\nValue: " + obj[key]);
}

Or in jQuery the $.each() if you need the closure, like this:

var obj = {"Name":"bb", "age":"10"};
$.each(obj, function(key, value) {
    alert("Key: " + key + "\nValue: " + value);
});

You can test both versions here .

Without jQuery you would use a for-in loop

var person = {"Name":"bb", "age":"10"};

for(var attr in person) {
  alert('Attribute: '+attr);
  alert('Value: '+person[attr]);
} 

... in jQuery:

var person = {"Name":"bb", "age":"10"};
$.each(person, function(attr, value) {
  alert('Attribute: '+attr);
  alert('Value: '+value);
});
var json = {"Name":"bb", "age":"10"}
for ( var i in json ) {
    console.log( json[i] );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM