skip to Main Content

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


  1. Chosen as BEST ANSWER

    I figure it out thanks to @Barman with a little bit of modification because i want them inside the Map() as Object.

    if (localHasMap.has('users')) {
       users = localHasMap.get('users');
       } else {
       users = new Map();
       users.set('user', username);
       }
    localHasMap.set('users', Object.fromEntries(users));
    

    Thank you all.


  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search