I am trying to loop through my array by using the key value from the .each function, but I don’t know how to do it. I essentially want to do value[‘key’][‘firstname’], but I don’t know the syntax.
The problem is that right now this function is not looping through my arrays. Each user has its own array object.
Perhaps a better way to explain my issue is that all of the users objects aren’t being added to the HTML. I double checked and the users are being loop through, but only the first one is being added. Here is the full code.
Is your val.users an object of users or is it an array of objects?
If it’s an array of objects it is most definitely better to use a for loop that it would be to use jQuery.each() as the latter is a lot slower than the former (in fact, jQuery.each() should ideally only be used to loop over jQuery / DOM objects, where it is faster).
If it is an object with objects, .each() is a nice shortcut, but a for…in loop might be better and faster.
I was actually able to get this working by making it into a function. The problem was that I was using push without running the whole loop. I agree with you too, I probably should use a for loop for the sake of speed. I wonder how much faster it actually is though.
“For in” iterates over EVERYTHING - including the methods. Do not use it without keeping that in mind. This becomes especially troublesome with the prototype.js framework since, as it’s name implies, it modifies the prototype of several major javascript objects. If you use prototype you pretty much commit to not using for … in; and if you use for … in you’re committing to not using prototype. That shouldn’t be an issue here since jQuery is the framework in place, but it is still important to keep in mind exactly what for…in does cause even if jQuery is your framework of choice you’ll eventually be called upon to maintain a prototype frameworked site and if you use for…in there you’re in for a world of hurt.
Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object
for (x in obj) {
if (obj.hasOwnProperty(x)) {
// ...
}
}
Yes, of course. typeof(x) == ‘function’ also works.
I’m not saying not to use for…in - I’m saying to be aware of what it does. It is not an iteration over object members. It is an iteration over everything, and if you don’t prepare for that things will get ugly fast.
PHP hands down. It has THREE iteration operators: " -> ", " :: ", and " \ " for namespaces to JavaScript’s 1 “.”. In variants of EMCA that have namespaces (Actionscript 3) namespaces are resolved with a . as well. And don’t get me started with the function libraries schizophrenic naming pattern. I love both languages and consider myself a master of both, but I’m painfully aware of each’s shortcomings. JavaScript has more bad code floating around, but that isn’t a fault of the language.