[英]How can I access a specific object in my array using JavaScript?
我創建了一個通過查詢器創建的動態對象數組。 但我無法弄清楚如何訪問數組中的特定對象編輯:這是控制台記錄我的數組的方式
例如,我如何訪問第二工程師 (Mark)?
請記住,數組將根據用戶輸入而變化
team = [
Manager {
name: 'Nicole',
id: '1',
email: 'nicole@gmail.com',
officeNumber: '5'
},
Engineer {
name: 'Zoe',
id: '2',
email: 'zoe@gmail.com',
github: 'zozo'
},
Engineer {
name: 'Mark',
id: '3',
email: 'mark@gmail.com',
github: 'emman'
},
Engineer {
name: 'Joe',
id: '4',
email: 'joe@gmail.com',
github: 'joey'
}
Intern {
name: 'Seb',
id: '5',
email: 'seb@gmail.com',
school: 'UWA'
}
]
使用find
方法。 如果沒有這樣的標記,則find
返回 null。
如果你想找到工程師馬克
const result = data.find(x => {
return x instanceof Engineer && x.name === 'Mark'
})
[更新] 如果你想找第二個工程師
const result = data.filter(x => {
return x instanceof Engineer
})[1]
正如Sepehr jozef提到的,結構不是那么方便。 如果我們采用他的結構,您可以通過.find方法找到它。
var team = [
{
name: 'Nicole',
id: '1',
email: 'nicole@gmail.com',
officeNumber: '5',
},
{
name: 'Zoe',
id: '2',
email: 'zoe@gmail.com',
github: 'zozo'
},
{
name: 'Mark',
id: '3',
email: 'mark@gmail.com',
github: 'emman'
},
{
name: 'Joe',
id: '4',
email: 'joe@gmail.com',
github: 'joey'
},
{
name: 'Seb',
id: '5',
email: 'seb@gmail.com',
school: 'UWA'
}
]
const mark = team.find(function(teamMember){
return teamMember.name === "Mark";
})
變量“mark”現在包含工程師“Mark”的對象。
首先,你的結構是錯誤的。
它應該是:
var team = [
{
name: 'Nicole',
id: '1',
email: 'nicole@gmail.com',
officeNumber: '5',
},
{
name: 'Zoe',
id: '2',
email: 'zoe@gmail.com',
github: 'zozo'
},
{
name: 'Mark',
id: '3',
email: 'mark@gmail.com',
github: 'emman'
},
{
name: 'Joe',
id: '4',
email: 'joe@gmail.com',
github: 'joey'
},
{
name: 'Seb',
id: '5',
email: 'seb@gmail.com',
school: 'UWA'
}
]
要獲得標記(2),您應該使用:
team[3].name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.