Reputation: 69
I have a JavaScript object. I try to get classid
from rgInventory.(someid).classid
and always getting undefined
.
My code (items is my object):
for (var i = 0; i < Object.keys(items.rgInventory).length; i++) {
console.log(items.rgInventory[i].classid);
}
Upvotes: 0
Views: 1408
Reputation: 350137
Your i
is not the key, but the sequence number of that key.
Change your code to:
var keys = Object.keys(items.rgInventory);
for (var i = 0; i < keys.length; i++) {
console.log(items.rgInventory[keys[i]].classid);
}
Note that with the for...of
syntax, it can be coded like this:
for (var key of Object.keys(items.rgInventory)) {
console.log(items.rgInventory[key].classid);
}
The for...in
syntax is more appropriate for iterating over object keys:
for (var key in items.rgInventory) {
console.log(items.rgInventory[key].classid);
}
You could also use the forEach
callback, with the nice second argument for setting this
:
Object.keys(items.rgInventory).forEach(function (key) {
console.log(this[key].classid);
}, items.rgInventory);
Upvotes: 2
Reputation: 5443
The problem is that you're using the i
variable as a lookup, instead of Object.keys(items.rgInventory)[i]
try this:
for (var i = 0; i < Object.keys(items.rgInventory).length; i++) {
console.log(items.rgInventory[Object.keys(items.rgInventory)[i]].classid);
}
But that is probably not how you want to do this lookup... This is a little cleaner:
Object.keys(items.rgInventory).forEach(function(key) {
console.log(items.rgInventory[key].classid)
})
Upvotes: -1