4

In Javascript is there a clever way to loop through the names of properties in objects in an array?

I have objects with several properties including guest1 to guest100. In addition to the loop below I'd like another one that would loop through the guestx properties without having to write it out long hand. It's going to be a very long list if I have to write the code below to results[i].guest100, that is going to be some ugly looking code.

for (var i = 0; i < results.length; i++) {
if (results[i].guest1 != "") {
    Do something;
}
if (results[i].guest2 != "") {
    Do something;
}
if (results[i].guest3 != "") {
    Do something;
}
etcetera...
}
Peter Bushnell
  • 918
  • 1
  • 13
  • 30

3 Answers3

5

Try this:

for (var i = 0; i < results.length; i++) {
    for (var j=0; j <= 100; j++){
        if (results[i]["guest" + j] != "") {
            Do something;
        }
    }
}
gdoron
  • 147,333
  • 58
  • 291
  • 367
3

Access properties by constructing string names in the [] object property syntax:

// inside your results[i] loop....
for (var x=1; x<=100; x++) {
  // verify with .hasOwnProperty() that the guestn property exists
  if (results[i].hasOwnProperty("guest" + x) {
     // JS object properties can be accessed as arbitrary strings with []
     // Do something with results[i]["guest" + x]
     console.log(results[i]["guest" + x]);
  }
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • It's hard to me to believe that you will ever have a property named `guest1`\ `guest2`..., which is not an ownProperty of the object. :) – gdoron May 12 '12 at 19:28
2

I think you'll find useful the "in" operator:

if (("guest" + i) in results[i]) { /*code*/ } 

Cheers

Sebas
  • 21,192
  • 9
  • 55
  • 109