Doug Molineux
Doug Molineux

Reputation: 12431

Javascript Object Access

I am using a Comet Push Engine called APE (Ajax Push Engine) and whenever I receive a realtime event I receive it in an javascript object called 'raw'.

So if for example if the raw object contains a 'location' value, I can print 'raw.location' and it will give me the value,

alert(raw.location);

So I have another object called currentSensor, which contains a value like this (in my example it would contain the string 'location'):

currentSensor.value

How do I programmatically use the currentSensor.value variable to access the 'raw' object? I have tried this:

var subsensor = currentSensor.sensorKey;

and then

alert(raw.subsensor);

But I keep getting undefined because the raw object doesn't contain a key called "subsensor" its actually "location". I hope this makes sense!

Thanks!

Upvotes: 2

Views: 1150

Answers (3)

Alin P.
Alin P.

Reputation: 44346

Here you go:

alert(raw[subsensor]);

The dot syntax cannot help you when you need to access variable indexes. You need to use the array access method.

Note: The dot access method is just syntactic sugar and is not really needed in any place, but it is useful for code readability.

For your entertainment:

"1,2,3"["split"](",")["join"]("|")

Upvotes: 1

Jan
Jan

Reputation: 8131

like this:

console.log(raw[currentSensor.value]);

Upvotes: 3

Quentin
Quentin

Reputation: 943100

When using dot-notation, you use a literal property name. If you want to use a string, use square bracket notation.

foo.bar === foo['bar'];

Strings can be variables.

baz = 'bar';
foo.bar === foo[baz];

Upvotes: 5

Related Questions