1

Heres the code.

const users = [{
  name: 'Homer', 
  role: 'clerk', 
  dob: '12/02/1988',
  admin: false 
}, 
{
  name: 'Lisa', 
  role: 'staff', 
  dob: '01/30/1965',
  admin: false 
}, 
{
  name: 'Marge', 
  role: 'associate', 
  dob: '09/10/1980',
  admin: true 
}];

I tried using console.log(users.name); to print out the names but if gives me Undefined. I'm having a hard time pulling any of the object properties and printing them out. Do I need to go within each individual object and add functions to call specific properties of each object?

Eugene Mihaylin
  • 1,736
  • 3
  • 16
  • 31
codeintech3
  • 57
  • 1
  • 4
  • 1
    users is an array, not an object. Iterate over it like an array with forEach or map, then you can call the dot properties of each object in the array. – jmargolisvt Nov 17 '18 at 20:15
  • You need to first access the object at the *index* in the array first. Like `users[0].name`. – slider Nov 17 '18 at 20:16
  • "*Do I need to go within each individual object ...*?" Yes. – [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Jonathan Lonowski Nov 17 '18 at 20:18

1 Answers1

0

users is an array.

You can either iterate through the entire array and print out useful properties from each and every user object. There are a few ways to do this, one being Array.prototype.forEach()


Or if you know the array index of one particular user that you want to get to, you can access their entire object like this:

user[0]

Which will be { name: 'Homer', role: 'clerk', dob: '12/02/1988', admin: false }

Or access a single one of their object properties like this:

user[0].name

Which will be 'Homer'

const users = [{
    name: 'Homer',
    role: 'clerk',
    dob: '12/02/1988',
    admin: false
  },
  {
    name: 'Lisa',
    role: 'staff',
    dob: '01/30/1965',
    admin: false
  },
  {
    name: 'Marge',
    role: 'associate',
    dob: '09/10/1980',
    admin: true
  },
]

users.forEach(user => {
  console.log(`${user.name} is a ${user.role}`)
})

console.log(`${users[0].name} is a ${users[0].role}`)
ksav
  • 20,015
  • 6
  • 46
  • 66