0

In the following code, I would like to retrieve person1 and person4 (the first person in the array) in a loop. This works when explicitly identifying the property. But when using a variable 'myField' to represent the property, it returns undefined... What would be the syntax to get the value?

JSFiddle: https://jsfiddle.net/8vr06Ltk/3/

    var companies = [
      { 
        "description":"company1", 
        "people": [{"name":"person1"},{"name":"person2"},{"name":"person3"}],
        "date":"2020-01-01"
      },
      { 
        "description":"company2", 
        "people": [{"name":"person4"},{"name":"person5"},{"name":"person6"}],
        "date":"2020-01-01"
      } 
    ]


var myField = "people[0].name";

for (var key in companies) {
  console.log(companies[key].people[0].name); /* correct: returns person1 and person4 */
  console.log(companies[key].myField); /* incorrect: undefined */
  console.log(companies[key][myField]); /* incorrect: undefined */
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Ted Scheckler
  • 1,389
  • 4
  • 16
  • 34
  • 1
    because it is looking for `{ "people[0].name" : "foo" }`. – epascarello Apr 24 '20 at 14:14
  • You could use a template string to pass in your variable ```var myField = "name"; for (var key in companies) { console.log(companies[key].people[0][`${myField}`]); /* correct: returns person1 and person4 */ }``` – portatlas Apr 24 '20 at 14:23
  • @portatlas Due to some other constraints, I need to have the entire structure of myField as a variable. – Ted Scheckler Apr 24 '20 at 14:29
  • Could you use something like jsonata https://try.jsonata.org/? you could pass in your variable as a query to get back the results you are looking for. – portatlas Apr 24 '20 at 14:44

0 Answers0