Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, how do I convert a string so it can be used to call a property?

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?

like image 260
joejoeson Avatar asked Nov 29 '22 18:11

joejoeson


1 Answers

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];
}
like image 122
SLaks Avatar answered Dec 05 '22 07:12

SLaks