Reputation: 111
I'm pretty new to JavaScript and started having trouble with JSON.
I have a object like so:
var users = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
Is there anyway I can do a jQuery $.each
selector to do something with each pair without knowing how many indexes there are?
Like so:
$.each(obj.firstname) {
// Do stuff for John then Anna then Peter
}
Upvotes: 1
Views: 311
Reputation: 4141
You might want to take a look at underscore.js, especially the pluck
method:
_.each(_.pluck(users, 'firstName'), function (firstName) {
// Do stuff
})
Upvotes: 0
Reputation: 8476
like this
$.each(users,function(key,val){
$.each(val, function(k, v){alert(k+" - "+v);});
});
Upvotes: 0
Reputation: 145428
Here is the basic usage:
$.each(users, function(i, user) {
var firstName = user.firstName;
var lastName = user.lastName;
// ...
});
Upvotes: 1
Reputation: 9167
More like:
$.each(users, function(i, data)) {
console.log(data.firstName);
});
Upvotes: 6