2

Possible Duplicate:
How to create object property from variable value in javascript?

How to access property name stored in variable like this?

var obj = {};

obj.foo = 'bar';
var propName = 'foo';

//I want something like this:
console.debug(obj.{propName});

Is there any possibility to do it without using eval()?

Community
  • 1
  • 1

2 Answers2

1

You can access the objects properties like:

myObject['property_name']

Try:

var obj = {};
obj.foo = 'bar';
var propName = 'foo';
console.log(obj[propName]);
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
0

Of cource you can:

​(function(){
    var obj = {};
    obj.foo = 'bar';

    var key = 'foo';

    document.write(obj[key]);
})()​
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73