I have created a dynamic array of objects which is created through inquirer. But I cannot figure out how to access a specific object in the array EDIT: this is how the console has logged my array
So for example, how can I access the 2nd Engineer (Mark)?
Keep in mind the array will change depending on the user input
team = [
Manager {
name: 'Nicole',
id: '1',
email: '[email protected]',
officeNumber: '5'
},
Engineer {
name: 'Zoe',
id: '2',
email: '[email protected]',
github: 'zozo'
},
Engineer {
name: 'Mark',
id: '3',
email: '[email protected]',
github: 'emman'
},
Engineer {
name: 'Joe',
id: '4',
email: '[email protected]',
github: 'joey'
}
Intern {
name: 'Seb',
id: '5',
email: '[email protected]',
school: 'UWA'
}
]
CodePudding user response:
Use find
method. If there is no such Mark then find
return null.
If you want find Engineer Mark
const result = data.find(x => {
return x instanceof Engineer && x.name === 'Mark'
})
[Update] If you want find the second Engineer
const result = data.filter(x => {
return x instanceof Engineer
})[1]
CodePudding user response:
As Sepehr jozef mentioned the strucure is not that handy. If we take his structure you can find it via the .find Method.
var team = [
{
name: 'Nicole',
id: '1',
email: '[email protected]',
officeNumber: '5',
},
{
name: 'Zoe',
id: '2',
email: '[email protected]',
github: 'zozo'
},
{
name: 'Mark',
id: '3',
email: '[email protected]',
github: 'emman'
},
{
name: 'Joe',
id: '4',
email: '[email protected]',
github: 'joey'
},
{
name: 'Seb',
id: '5',
email: '[email protected]',
school: 'UWA'
}
]
const mark = team.find(function(teamMember){
return teamMember.name === "Mark";
})
The variable "mark" contains now the object of the engineer "Mark".
CodePudding user response:
first of all, your structure is wrong.
it should be:
var team = [
{
name: 'Nicole',
id: '1',
email: '[email protected]',
officeNumber: '5',
},
{
name: 'Zoe',
id: '2',
email: '[email protected]',
github: 'zozo'
},
{
name: 'Mark',
id: '3',
email: '[email protected]',
github: 'emman'
},
{
name: 'Joe',
id: '4',
email: '[email protected]',
github: 'joey'
},
{
name: 'Seb',
id: '5',
email: '[email protected]',
school: 'UWA'
}
]
and to get mark(2) you should use:
team[3].name