jambuls
jambuls

Reputation: 111

How to loop through JSON per group

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

Answers (5)

Adrian Heine
Adrian Heine

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

Anton
Anton

Reputation: 32581

for(var key in users){
console.log(users[key].firstName)
}

Upvotes: 0

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

like this

$.each(users,function(key,val){
 $.each(val, function(k, v){alert(k+" - "+v);});
});​  

fiddle

Upvotes: 0

VisioN
VisioN

Reputation: 145428

Here is the basic usage:

$.each(users, function(i, user) {
    var firstName = user.firstName;
    var lastName = user.lastName;
    // ...
});

Upvotes: 1

Chris Dixon
Chris Dixon

Reputation: 9167

More like:

$.each(users, function(i, data)) {
   console.log(data.firstName);
});

Upvotes: 6

Related Questions