Dynamic property names for a Javascript object loop

Is there a smart way in Javascript to iterate over property names in objects in an array?

I have objects with several properties, including guest1 to guest100. In addition to the loop below, I would like to get another one that will loop over the guestx properties without writing down its long arm. This will be a very long list, if I need to write the code below for the [i] .guest100 results, it will be some ugly 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...
}
+3
source share
3 answers

Try the following:

for (var i = 0; i < results.length; i++) {
    for (var j=0; j <= 100; j++){
        if (results[i]["guest" + j] != "") {
            Do something;
        }
    }
}
+5
source

Access properties by creating row 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]);
  }
}
+2
source

, "in":

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

+2

All Articles