ReasonPlay ReasonPlay - 2 months ago 5
Javascript Question

JavaScript get info from object

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);
}

Answer

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);
Comments