Is there any way to add an array of objects into a Map() ?
I want to add a username from the array each time i call the function add().
Quick example:
let localHashMap = new Map();
let arr = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff']; // etc
function add(arrayNumber) {
addToMap(arr[arrayNumber]);
}
function addToMap(username) {
localHashMap.set('users', { 'user': username }); // <-- add? put? set?
let obj;
if (localHashMap.has('users')) {
obj = localHashMap.get('users');
}
//Then i will use a loop to get the results
console.log(obj);
//Output example
//{ user: fff }
//{ user: ddd }
//{ user: aaa }
//etc
}
Thanks in advance!
I try to figure it out but no luck at all..
2
Answers
I figure it out thanks to @Barman with a little bit of modification because i want them inside the Map() as Object.
Thank you all.
Fetch the array from the
Map
; if it doesn’t exist, initialize it to an empty array. Then push the new item onto the array.