0

Possible Duplicate:
Get property of object in JavaScript

If I have the following:

var test ='bar';

var sections = {
    foo: 'value1',
    bar: 'value2',
    baz: 'value3'
};

I can use sections.foo to output 'value1'. Thats fine. However what if I want to get the value from sections according to another variable. Although this doesnt work what I mean is something like:

sections.test

Where test is the variable declared earlier, so the value returned would be 'bar'.

I dont work a awful lot with js so any help would be appreciated :) .. or if im approaching this the wrong way, feel free to say.

thanks

-->EDIT

The reason I wanted to do this is because the variable 'test' will be coming from the url and then I just wanted to load up further information depending on what page the user was on. :)

0

3 Answers 3

4

Use [] instead of ..

sections[test] // value2
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for beating me while I was fiddling - jsfiddle.net/YgcDf
Perfect. Cant believe it was so simple lol. Didnt realise it can just be accessed like an array. Thanks
0

Where test is the variable declared earlier, so the value returned would be 'bar'.

if (sections.hasOwnProperty(test)) return test;

But what you probably meant was

if (sections.hasOwnProperty(test)) return sections[test];

Comments

0

You can access it as an array index, like so: sections[test]. But, AFAIK, Javascript doesn't have any concept of variable variables, like how in php you can do $sections->$test.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.