1

I have a json object I am querying in jquery and having trouble using the values stored in jquery variables. Example:

$tops= json.tops
$color = "blue";

If I console.log($tops.blue); I get the expected result. But, if I console.log($tops.$color); I get 'undefined'.

Can anyone explain what I am doing wrong/what the difference is?

5
  • 2
    can you post the code you already have tried? Commented Sep 28, 2015 at 17:26
  • Was json ever parsed? What gets returned when you type in typeof json? Commented Sep 28, 2015 at 17:29
  • Why would you expect $tops.blue to be the same as $tops.$color? You haven't assigned $tops.$color. Commented Sep 28, 2015 at 17:30
  • 1
    You probably mean $color = 'blue' (with quotes), and $tops[$color]. Commented Sep 28, 2015 at 17:31
  • @JohnBupit the code does have quotes just left them out here by mistake, sorry! Commented Sep 28, 2015 at 17:33

1 Answer 1

1

From your console.log example, my thought is that what you are looking for is $tops[$color]. $tops.$color would look for a property of '$color'.

From your code sample, I think you would need $color = 'blue' (blue being a string), as currently it would be the value of a variable named blue.

Also, perhaps this would be helpful: JavaScript property access: dot notation vs. brackets?

Sign up to request clarification or add additional context in comments.

6 Comments

I edited my question to include "", I left those out by mistake but they are in my code. I wouldnt use brackets because i"m not accessing an array
@TatianaFrank If you look at the link I included, you will see one of the uses is 'selection of properties using variables'. The array access notation treats the object as a dictionary, with property names being the keys. Essentially obj.x == obj['x'].
ahh that makes sense. Thank you!
I was just thrown off by the fact that it works for $tops= json.tops but not the rest... Why is that by the way?
@TatianaFrank I'm not sure what you mean by "works" with regard to $tops = json.tops? I presume there exists a property named tops on the json object? The . notation will treat whatever is on the right side of it as an identifier, and look for a property with that name. So .blue will look for property blue, .tops will look for property tops, and .$color will look for property $color. At no point do the variables in scope matter for that expansion.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.