Search code examples
javascriptmaps

Adding elements into arrays held as values in a map


I really struggle with the following. I have a simple Map, where for each key there is a value, which is an array.

MyMap= {
'Anna' => [ 'Item1', 'Item2' ]
}

However, I would need to extend the arrays for particular keys, i.e. add elements to them, but just cannot figure out the syntax.

I tried

 myMap.set(name,myMap.get(name).push(item))

Solution

  • you do not have to set again. Map holds a reference to the original array and when you push it modifies the array

    const map = new Map();
    
    map.set('Anna', ['Item1','Item2']);
    console.log(...map)
    
    map.get('Anna').push('Item3')
    console.log(...map)