tags:

views:

70

answers:

5

How to get the value of key a and 'a' in javascript?

var obj = {a:1,'a':2}
+4  A: 

The first key a will be overwritten by the second 'a'.

obj.a will return 2.

If your key name is a valid Javascript identifier or a number, Javascript will allow you to omit the quotes in key names. In practice, however, it's probably better to train yourself to always use quotes, to avoid confusion like this, and also because JSON requires them.

Triptych
+1  A: 

There isn't any difference.

alert([
    obj.a,
    obj['a']
].join("\n")); // returns 2 in both cases
w35l3y
+7  A: 

You can't - they are same key, and that initialiser will create an object with a single element 'a' with value '2'. Try this:

var obj = {a:1,'a':2};

for ( var i in obj )
{
    alert(i + '=' +  obj[i] );
}

And you'll just get "a=2' in response.

Paul Dixon
+1  A: 

If you not sure about key - use iteration

for(var k in obj)
    alert(k + "=" + obj[k])

When you know key exact value use obj[k]

Dewfy
A: 

obviously, 'a' is the one-character string with a lowercase a as content; but what do you expect to be the other key? if you want it to be the value of a variable called a, then the curly braces syntax won't help you. Unlike Python, this syntax assumes the keys are strings, and quotes are optional.

You'd have to do something like this:

var a = 'givenkey'
var obj = {}
obj[a] = 1
obj['a'] = 2

this would create an object equivalent to:

var obj = {'givenkey':1, 'a':2}
Javier