简体   繁体   中英

JavaScript6: adding element (key, value) to a ES6 map

In jsx I have a map like:

var myMap=Map([['rowNumber', '30'], ['id', '80'], ['firstName', '180'], ['lastName', '180'], ['mobile', '180'], ['username', '180'], ['password', '180']])

how can I do programatically add new element like: ['ssn', '12'] to this map?

You're looking for the set method :

myMap.set('ssn', '12');

If you have an entry tuple, you can use

const newEntry = ['ssn', '12'];
myMap.set(newEntry[0], newEntry[1]);
// or also
myMap.set(...newEntry) // however that might be confusing

Take a look at the Map reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

You can add items to a map with: myMap.set(keyString, "value associated with 'a string'");

You can use set() method with spread syntax to add array of two elements as key and value.

 var myMap = new Map([['rowNumber', '30'], ['id', '80'], ['firstName', '180'], ['lastName', '180'], ['mobile', '180'], ['username', '180'], ['password', '180']]) myMap.set(...['ssn', '12']) for(var i of myMap) console.log(i) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM