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]....

7
  • a.a is getting property a of object a. a[a] is trying to get an array element. Commented Jul 12, 2013 at 9:49
  • @Archer Thanks, but how I get the property a dynamically? Commented Jul 12, 2013 at 9: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. Commented Jul 12, 2013 at 9:51
  • The accepted answer in the following question has a good explanation: stackoverflow.com/questions/17189642/… Commented Jul 12, 2013 at 9: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<array.length; i++ loop. Commented Jul 12, 2013 at 9:54

3 Answers 3

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].

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

Comments

1

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

Comments

1

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

Comments

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.