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 });

1
  • 1
    Side note, what you are calling a HashMap is just an Object in javascript. Commented Nov 10, 2017 at 22:05

2 Answers 2

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

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

Comments

2

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

laneMap[eventIDs[1]] = currlane;

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.