1

Let a = {a: 1, b:2}, whichs shows in console Object {a: 1, b: 2}.

When I do a.a I get 1. When I do a[a] I get undefined.

Is it normal ?

I'm asking this because I need to get values from dynamic keys. a[product1], a[product2]....

Alex
  • 2,036
  • 4
  • 22
  • 31
  • `a.a` is getting property `a` of object `a`. `a[a]` is trying to get an array element. – Reinstate Monica Cellio Jul 12 '13 at 09:49
  • @Archer Thanks, but how I get the property a dynamically? – Alex Jul 12 '13 at 09:50
  • 1
    @Archer - No. The former is getting the property `a` the latter is getting the property with the name that is the same as the string value of `a`. It has nothing to do with arrays. – Quentin Jul 12 '13 at 09:51
  • The accepted answer in the following question has a good explanation: http://stackoverflow.com/questions/17189642/difference-between-using-bracket-and-dot-notation/ – Alberto Zaccagni Jul 12 '13 at 09:51
  • If your keys are a numeric sequence, then you should be using an array (`{ product: [val, val, val] }`) and a `for i=1; i – Quentin Jul 12 '13 at 09:54
  • @Quentin I never knew that - thanks :) However, it *could* be an array so to dismiss it completely was incorrect. Thanks for the new thing for the day though. Name/Value pairs in JS made easy! – Reinstate Monica Cellio Jul 12 '13 at 09:58
  • @Archer — Arrays are a kind of object. I mean that there was nothing special about arrays for this. It applies to any kind of object. – Quentin Jul 12 '13 at 10:57

3 Answers3

10

Yes, this is normal.

a[a] is the same as a[a.toString()] which is the same as a['[object Object]'] and you haven't defined a property with that name in the object.

If you want to use square bracket notation to access a property called a then you have to pass a string with the value a: a['a'] or var prop = 'a'; a[prop].

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Can you try a['a'] this will return the value of a

vinothini
  • 2,606
  • 4
  • 27
  • 42
1

try giving like this a["a"] or a["product1"]

wizzardz
  • 5,664
  • 5
  • 44
  • 66