Search code examples
javascriptnode.js

add object from array into a Map() Javascript/Node


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..


Solution

  • 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.

    let localHashMap = new Map();
    let arr = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff']; // etc
    
    function add(arrayNumber) {
      addToMap(arr[arrayNumber]);
    }
    
    function addToMap(username) {
      let users;
      if (localHashMap.has('users')) {
        users = localHashMap.get('users');
      } else {
        users = [];
        localHashMap.set('users', users);
      }
      users.push({user: username});
    
      console.log(users);
    }
    
    add(3);
    add(5);
    add(2);