views:

35

answers:

3

So, I have an associative array and the keys in the array are properties of an object. I want to loop through the array and in each interation do something like this:

Object.key

This however does not work and results in returning undefined rather than the value of the property.

Is there a way to do this?

Thanks

A: 

Yes. Assuming key is a string, try myObject[key]

spender
+2  A: 

You should use the bracket notation property accessor:

var value = object[key];

This operator can even evaluate expressions, e.g.:

var value = object[condition ? 'key1' : 'key2'];

More info:

Don't forget that the methods of Array objects, expect to work with numeric indexes, you can add any property name, but it isn't recommended, so instead intantiating an Array object (i.e. var obj = []; or var obj = new Array(); you can use a simple object instance (i.e. var obj = {} or var obj = new Object();.

CMS
+2  A: 

You can use a for ... in loop:

for (var key in obj) {
    //key is a string containing the property name.

    if (!obj.hasOwnProperty(key)) continue;  //Skip properties inherited from the prototype

    var value = obj[key];
}
SLaks