1

I have a javascript object defined below:

var user = { name:'Allen', age:'26', gender:'male'}

I want to reference the user property user.name via string such as below:

var string = "name";
var username = user.string;

This doesn't work, how would I go about this?

EDIT: just to clarify, I want user.string to be the equivalent of user.name - some might ask why I don't just call user.name, and this is because I have an array of strings that I would like to evaluate for the object.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Allen
  • 3,601
  • 10
  • 40
  • 59
  • 2
    var username = user[string]? – sinisake Mar 02 '14 at 02:12
  • @cokeman19 not quite... – Matt Ball Mar 02 '14 at 02:13
  • possible duplicate of [Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name) and [a pile of others](http://stackoverflow.com/questions/17832583/create-an-object-with-dynamic-property-names#comment26027295_17832583) – Matt Ball Mar 02 '14 at 02:16

2 Answers2

5

You'd do something like

var string = 'name';
var username = user[string];

to access the property in the string.

Right now your code is trying to access an undefined 'string' property on the user.

Shadaez
  • 412
  • 3
  • 13
0

Not 100% sure about what you mean. You can access the name property with user.name. It will return Allen.

var user = { name:'Allen', age:26, gender:'male' }

var name = user.name; // 'Allen'
var age = user.age; // 26
var gender = user.gender; // 'male'
Spedwards
  • 4,167
  • 16
  • 49
  • 106
  • 1
    basically, I want to get the REFERENCE of the string. for instance, if I have a var x = "name", then I want user.x to be the equivalent of user.name – Allen Mar 02 '14 at 02:15