0

I'm trying to dynamically populate a HashMap in jQuery, and am following this example: https://stackoverflow.com/a/4247012/1005607 Orig Question: How to create a simple map using JavaScript/JQuery

I need to add a hash entry where the key comes from an array item, and the value is a variable. But I'm getting an error. What's wrong? This should be equivalent to populating "item2" -> 2 in the HashMap. I would be able to get 2 by invoking laneMap.get("item2").

var laneMap = {};

var eventIDs = [];
eventIDs.push('item1');
eventIDs.push('item2');

var currlane = 2;

laneMap.push({eventIDs[1] : currlane });
gene b.
  • 10,512
  • 21
  • 115
  • 227

2 Answers2

2

You can only use .push with an array. Here's how to assign a dynamic object property:

laneMap[eventIDs[1]] = currlane;

James
  • 20,957
  • 5
  • 26
  • 41
2

You can't add key/value pair using push. There are two ways of doing it Using dot notation:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

var laneMap = {};

var eventIDs = [];
eventIDs.push('item1');
eventIDs.push('item2');
   
var currlane = 2;
laneMap.key = currlane-1;
laneMap[eventIDs[1]] = currlane ;
console.log(laneMap);

P.S.- You can't use [] in dot notation

Sanchit Patiyal
  • 4,910
  • 1
  • 14
  • 31