在下面的代码中,我想循环检索person1和person4(数组中的第一个人)。明确标识属性时,此方法有效。但是,当使用变量“ myField”表示属性时,它返回未定义的...获取值的语法是什么?
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 */
}