1

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
}
1
  • This has nothing to do with JSON, btw, it's just a normal JavaScript data structure used in a normal JavaScript script. Oct 17, 2012 at 9:29

5 Answers 5

6

More like:

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

Here is the basic usage:

$.each(users, function(i, user) {
    var firstName = user.firstName;
    var lastName = user.lastName;
    // ...
});
3
  • alert(users[0].firstname); //works $.each(users, function(i, obj) { alert(users.firstName);//gives undefined });
    – jambuls
    Oct 17, 2012 at 9:35
  • sorry cant get it to space properly
    – jambuls
    Oct 17, 2012 at 9:39
  • @user1752451 The problem is that you use incorrect variables. Just copy the solution which is illustrated in the answer, and it will work.
    – VisioN
    Oct 17, 2012 at 9:42
0

like this

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

fiddle

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

You might want to take a look at underscore.js, especially the pluck method:

_.each(_.pluck(users, 'firstName'), function (firstName) {
    // Do stuff
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.