1

I have a problem in declaring a inicialiting an object. When I define an object and pass by reference a string does not recognize me and fails. The object is as follows:

markerGroups = {"america": [], "europa": [], "asia": [],"africa": [], "oceania": [] };

Well, it works correctly, but if I change, for example, "america" ​​putting var amer = "america"​​, like this:

var amer = "america"; 
markerGroups = {amer: [], "europa": [], "asia": [],"africa": [], "oceania": [] };

It does not work. What i have to do for resolve this?

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • Unlike Python dicts, in a JavaScript Object Literal, property names are *always* literal values and are *never* expressions: `{a: "foo"}` and `{'a': "foo"}` and `{"a": "foo"}` are all equivalent. – user2864740 Feb 17 '14 at 19:04
  • I don't know if it's a duplicate of *that* question, as the *question* seems to start where I think the *answer* to this should end.. (that being said, there are plenty of duplicates) – user2864740 Feb 17 '14 at 19:06
  • http://stackoverflow.com/questions/9708192/use-a-concatenated-dynamic-string-as-javascript-object-key?lq=1 , http://stackoverflow.com/questions/1998735/dynamic-object-literal-in-javascript?lq=1 – user2864740 Feb 17 '14 at 19:07
  • I'm sorry if there are a duplicate :( – user2209769 Feb 17 '14 at 19:40

2 Answers2

2

In JavaScript, you don't need to quote your object keys. So amer: [] is creating the literal key "amer".

You need to use the [] method to do this:

var amer = "america"; 

markerGroups = {...};
markerGroups[amer] = [];
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

something like this;

var markerGroups = {}
var amer = "america"; 
markerGroups[amer] = [];
MamaWalter
  • 2,073
  • 1
  • 18
  • 27