1

I'm trying to do the following, is this possible?

var objectName = {prop: 'value'};

var stringName = 'objectName';

console.log([stringName]) // output {prop: 'value'}

Update: There are actually a few ways to do this, which I was already aware of but it seems this was more an issue to do with how babel compiled imported objects. Apologies for such a dull question...

zilj
  • 619
  • 1
  • 7
  • 13

3 Answers3

3

If it's in global context you can get it from window object

var objectName = {prop: 'value'};

var stringName = 'objectName';

console.log(window[stringName]) // output {prop: 'value'}

A better approach is to define it inside an object and get value from the object for future reference.

varvar obj = {
  objectName: {
    prop: 'value'
  }
};

var stringName = 'objectName';

console.log(obj[stringName]) // output {prop: 'value'}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

If you do this in the frontend, you could do console.log(window[stringName]).

idleherb
  • 1,072
  • 11
  • 23
-1

Depends, are you trying to access a property on the global object? If so then no its not possible. You can however access object properties like so.

var myVariable = {
  prop: 'something'
};

var propName = 'prop';

console.log(myVariable[propName]);

It is good practice not to pollute the global scope with variables anyway.

Amonn
  • 84
  • 6
  • It is possible to access a global object. As it will be in window or you could use eval() – Liam Jun 09 '16 at 15:15
  • The title suggests, and the question was about referencing an object property by name. My point is that you cannot access the global scope in the way suggested. Instead in JavaScript you can access an objects properties dynamically but you first must specify the object. Be it the window object or anything else. – Amonn Jun 09 '16 at 15:44