Dynamic property names for loop of object Javascript - Stack Overflow

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

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...
}

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...
}
Share Improve this question asked May 12, 2012 at 18:47 Peter BushnellPeter Bushnell 9381 gold badge13 silver badges32 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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;
        }
    }
}

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]);
  }
}

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

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

Cheers

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744117312a4559234.html

相关推荐

  • Dynamic property names for loop of object Javascript - Stack Overflow

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

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信