The Javascript Map set()
method adds or updates a key-value pair in Map object.
It returns the Map object.
myMap.set(key, value)
Using set()
let myMap = new Map(); console.log(myMap);/*from w w w . jav a2 s .c o m*/ // Add new elements to the map myMap.set('bar', 'foo'); console.log(myMap); myMap.set('key', 'foo'); console.log(myMap); myMap.set(1, 'foobar'); console.log(myMap); // Update an element in the map myMap.set('key', 'baz'); console.log(myMap);
Using the set()
with chaining
The set()
method returns back the same Map object, we can chain the set()
method call:
let myMap = new Map(); console.log(myMap);/*from ww w. j a va 2 s . co m*/ // Add new elements to the map with chaining. myMap.set('bar', 'foo') .set(1, 'foobar') .set('key', 'foobar') .set(2, 'baz'); console.log(myMap);