Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic property names for loop of object Javascript

Tags:

javascript

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...
}
like image 983
Peter Bushnell Avatar asked Sep 02 '25 04:09

Peter Bushnell


1 Answers

Try this:

for (var i = 0; i < results.length; i++) {
    for (var j=0; j <= 100; j++){
        if (results[i]["guest" + j] != "") {
            Do something;
        }
    }
}
like image 99
gdoron is supporting Monica Avatar answered Sep 04 '25 21:09

gdoron is supporting Monica