Reputation: 2046
I have a javascript object:
[{ id: 11,
username: 'me',
firstname: 'my',
lastname: 'name',
}]
I'm trying to get the value of the firstname
property, but I can't seem to do it. I thought I knew how to work with objects until this. I'm developing this within Node.js, which I don't think matters, but I'm new to node, so who knows.
Console.log reads the following for my different attempts:
console.log(typeof(user_info))
= object
console.log(typeof(user_info[0]))
= object
console.log(user_info)
= [{ id: 11,
username: 'me',
firstname: 'my',
lastname: 'name',
}]
console.log(user_info[0].firstname)
= TypeError: Cannot read property 'firstname' of undefined
console.log(user_info[0]['firstname'])
= TypeError: Cannot read property 'firstname' of undefined
console.log(user_info['firstname'])
= undefinded
console.log(user_info.firstname)
= undefinded
var output = '';
for(var prop in user_info){
output += prop + ': ' + user_info[prop] + '; ';
}
console.log(output);
=
0:[object Object];
for(var prop in user_info[0]){
console.log(user_info[0][prop]);
}
=
11
me
my
name
I feel like I'm so close with the last shot, but I can't wrap my mind around how to get the key while using the for in
loop. What am I missing?
**I'm using Firefox, if that helps. And though I like Chrome, in the current setting, I'm unable to use Chrome*
Upvotes: 0
Views: 2334
Reputation: 1623
for(var prop in user_info[0]){
console.log('key = ', prop);
console.log('value = ', user_info[0][prop]);
}
prop - key what you need
Upvotes: 2
Reputation: 8340
You want key in for... in
?
How about this...
for(var prop in user_info[0]){
console.log(prop);
}
FWIW:
console.log(user_info[0]['firstname'])
prints 'my'
in chrome.
Upvotes: 1