简体   繁体   中英

How can I access a specific object in my array using JavaScript?

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: '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'
  }
]

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]

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: '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";
})

The variable "mark" contains now the object of the engineer "Mark".

first of all, your structure is wrong.

it should be:

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'
    }
]

and to get mark(2) you should use:

team[3].name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM