我有下面的對象,我想獲得職員數組中的第一項的名稱。使用javascript創建訪問對象中的項的鍵
const staffObj = {
"staff":[
{ "name": "tom"},
{ "name": "sam"}
]
}
我可以做任何
console.log(staffObj['staff'][0]['name'])
console.log(staffObj.staff[0].name)
但我想要做的就是從一個變量來訪問我的目標,我創建 如
const currentField = 'name'
const firstITem = ['staff'][currentField ]
console.log(firstITem,staffObj.firstITem)
什麼是正確的做到這一點語法來實現這個?
也許看看[用字符串鍵訪問嵌套的JavaScript對象](https://stackoverflow.com/q/6491463/218196) –
這是不可能的(除非你在對象上實現一個getter或代理) – Bergi