16

How can I achieve the following using ImmutableJS:

myMap.get(key).push(newData);

c0deNinja
  • 3,956
  • 1
  • 29
  • 45
Chopper Lee
  • 1,557
  • 2
  • 11
  • 30

2 Answers2

37

You can do as follows: (see this JSBin)

const myMap = Immutable.fromJS({
  nested: {
    someKey: ['hello', 'world'],
  },
});

const myNewMap = myMap.updateIn(['nested', 'someKey'], arr => arr.push('bye'));

console.log(myNewMap.toJS());
// {
//  nested: {
//    someKey: ["hello", "world", "bye"]
//  }
// }

Since myMap is immutable, whenever you try to set/update/delete some data within it, it will return a reference to the new data. So, you would have to set it to a variable in order to access it (in this case, myNewMap).

Brian Park
  • 2,557
  • 22
  • 21
  • Beware that that arr.push will actually return not a updated array itself but a new size of it... unless it's immutable too :) – kboom Feb 18 '17 at 09:02
7

If the array referenced at the key is a plain javascript array - then you will actually mutate that value - so your code will work as expected (ie - myMap will contain a mutable/mutated array at 'key' with the newData pushed in.) However, this kind of defeats the purpose of immutability so I would recommend that the key in myMap reference an Immutable.List. In which case you'll want to do:

var newMap = myMap.set('key', myMap.get('key').push(newData))