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?
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?
Share Improve this question edited Sep 19, 2012 at 19:40 James McMahon 49.6k69 gold badges210 silver badges288 bronze badges asked Apr 19, 2010 at 0:59 joejoesonjoejoeson 1,1071 gold badge10 silver badges14 bronze badges3 Answers
Reset to default 10You 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];
}
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:
- Member operators
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();
.
Yes. Assuming key
is a string, try myObject[key]