Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add data to a javascript map

Is there a way I can dynamically add data to a map in javascript. A map.put(key,value)? I am using the yui libraries for javascript, but didn't see anything there to support this.

like image 536
stevebot Avatar asked Jun 03 '10 14:06

stevebot


Video Answer


2 Answers

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

like image 127
Pointy Avatar answered Oct 20 '22 02:10

Pointy


Javascript now has a specific built in object called Map, you can call as follows :

   var myMap = new Map()

You can update it with .set :

   myMap.set("key0","value")

This has the advantage of methods you can use to handle look ups, like the boolean .has

  myMap.has("key1"); // evaluates to false 

You can use this before calling .get on your Map object to handle looking up non-existent keys

like image 76
NiallJG Avatar answered Oct 20 '22 04:10

NiallJG