0
user = {
  lastName: "Jones",
  phone: 12345,
  email: "mike@gmail.com",
  name: "Mike"
}

for(i = 0; i < Object.keys(user).length; i++) {
  theKey = Object.keys(user)[i]
  console.log(user.theKey)
}

The current output is:

undefined
undefined
undefined
undefined 

expected is:

Jones
12345
mike@gmail.com
Mike

I know there are other ways to do it but I was wondering what my issue was in doing it this way?

Object.keys(user)[i]

returns

lastName
phone
email
name

so I dont understand why it would return undefined in the dot notation. What could I do to return the values of this object in this way?

paperboi
  • 1
  • 1

3 Answers3

1

thereis no such property as 'theKey' in 'user' Object

try this one

console.log(user[theKey])

Dynamically access object property using variable

drps
  • 21
  • 4
0

i believe you can just do Object.values instead of Object.keys, i also think you don't need theKey variable, i think you can just do console.log(Object.values[i])

0

You can use Object.entries to get both the key and the value. You can also you object.Keys but you have to change it a bit. see below.

user = {
  lastName: "Jones",
  phone: 12345,
  email: "mike@gmail.com",
  name: "Mike"
}

Object.keys(user).map((e) => console.log(`key=${e}  value=${obj[e]}`));

Object.entries(user).forEach(([key, value]) => console.log(`key=${key} value=${value}`));
ThomasK
  • 300
  • 1
  • 8