Dynamic property names for loop of object Javascript

前端 未结 3 1319
北荒
北荒 2020-12-21 09:57

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 guest1

相关标签:
3条回答
  • 2020-12-21 10:21

    Try this:

    for (var i = 0; i < results.length; i++) {
        for (var j=0; j <= 100; j++){
            if (results[i]["guest" + j] != "") {
                Do something;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-21 10:33

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

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

    Cheers

    0 讨论(0)
  • 2020-12-21 10:34

    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]);
      }
    }
    
    0 讨论(0)
提交回复
热议问题