Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set object key to value of variable - why have two different ways?

Tags:

javascript

In JavaScript, if you have the following code:

  var map_id = 100;
  var myobj = {};
  myobj[map_id] = 6;
  var myobj2 = { map_id : 6 };
  console.log(myobj, myobj2);

The console output is as follows:

{ '100': 6 } { map_id: 6 }

Questions:

  1. Why does JavaScript syntax work differently in these two different cases - why is they key in myobj2 set to the literal map_id rather than 100? What is the reasoning behind having this difference?
  2. Is there any way to set the key to the value of the map_id variable in a compact, one-line way, rather than having to define the object separately first?

Thanks.

like image 640
Richard Avatar asked Oct 26 '11 09:10

Richard


People also ask

Can JavaScript object have multiple keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Can a JavaScript object key Be a string?

Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.


1 Answers

Is there any way to set the key to the value of the map_id variable in a compact, one-line way, rather than having to define the object separately first?

No. Sorry.

(Unless you count putting both statements on one line separated by a semicolon, which I don't.)

Why does JavaScript syntax work differently in these two different cases - why is they key in myobj2 set to the literal map_id rather than 100? What is the reasoning behind having this difference?

Good question. I don't know, and I've never been able to think of a good reason. I think it would make much, much more sense if the key names were treated like expressions the same as pretty much everything else in JavaScript, i.e., as a literal if quoted ({ "map_id" : 6 }), and as a variable if not quoted ({map_id : 6 }).

like image 67
nnnnnn Avatar answered Oct 31 '22 17:10

nnnnnn