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?

Tatiana Frank
  • 418
  • 5
  • 22

1 Answers1

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?

Community
  • 1
  • 1
ryachza
  • 4,460
  • 18
  • 28
  • 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 – Tatiana Frank Sep 28 '15 at 17:34
  • @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']`. – ryachza Sep 28 '15 at 17:37
  • ahh that makes sense. Thank you! – Tatiana Frank Sep 28 '15 at 17:41
  • 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? – Tatiana Frank Sep 28 '15 at 17:44
  • @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. – ryachza Sep 28 '15 at 17:47
  • @TatianaFrank Also, in case it's helpful, jQuery is not relevant here - everything you're doing is just JavaScript, and the `$` means nothing special. It just happens that JavaScript does not assign any special meaning to the `$` character and it can be used inside identifiers (function/variable names). – ryachza Sep 28 '15 at 17:50