0

JS noob here. If I have a string, how can I call an attribute from an object which has the same name as the string?

var carrot = {
    'vitaminA': 150,
    'vitaminC': 100
};

var cucumber = {
    'vitaminA': 10,
    'vitaminC': 12

};

var vegetable = 'cucumber'
alert(vegetable.vitaminC) // this doesn't work 

Note: this is a simplified version of the problem I'm working on, so I can't simply say alert(cucumber.vitaminC) -- I have to operate on the object based on the string

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – Ian Apr 08 '13 at 21:05

3 Answers3

3

You can have it like:

window[vegetable].vitaminC

But I highly suggest containing these guys in an object that is not the global object window:

var vegetables = {
  cucumber : {
    vitaminA: 10,
    vitaminC: 12
  },
  carrot : {
    vitaminA: 150,
    vitaminC: 100
  }
};

var vegetable = 'cucumber';
alert(vegetables[vegetable].vitaminC);
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 1
    +1: beat me to it. Although personally I like me some semicolons :) – Cᴏʀʏ Apr 08 '13 at 21:08
  • Thanks, why do you suggest not containing it in the global object window? –  Apr 09 '13 at 00:13
  • @BenDavidow because `window` is the global object, and a good practice is to **not** "pollute" the global space with a lot of stuff. There are a lot of reasons why. – Joseph Apr 09 '13 at 02:44
2

You can do this if you know the scope. If the scope is global, you can access it like this:

var vegetable = window['cucumber'];
alert(vegetable.vitaminC);
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

I would change your structure a little bit to get your objects out of the global scope. You can do this by simply adding a new object to contain your vegetables:

var vegetables = {
    carrot: {
        'vitaminA': 150,
        'vitaminC': 100
    },
    cucumber: {
        'vitaminA': 10,
        'vitaminC': 12
    }
};

And then you'd be able to access your properties by name (with a string) using [] notation:

vegetables['cucumber'].vitaminC; // 12

Or

vegetables['cucumber']['vitaminC']; // 12
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • They don't need to change the structure to access the properties. Although I do agree they should change the structure :) – Ian Apr 08 '13 at 21:06