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 */
}