2

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!

3 Answers 3

5

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];
Sign up to request clarification or add additional context in comments.

Comments

3

like this:

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

Comments

1

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"]("|")

3 Comments

Thank you guys! I guess I'll go with this one since it was the quickest :)
By 'quickest' do you mean 'at the top when you sort with newest first'? :)
Right, first one listed, but thank you all of your advice was helpful, I upvoted each of them

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.