Adding values to collections
The two main collection types on which we'll call persistent change methods are lists and maps. When you call a method to add a new value to a collection, you have to store the result somewhere because persistent changes only create data; they never destroy data.
Pushing values to lists
You can push a new value onto a list using the push()
method, as follows:
const myList = List.of(1, 2, 3); const myChangedList = myList.push(4); console.log('myList', myList.toJS()); // -> myList [ 1, 2, 3 ] console.log('myChangedList', myChangedList.toJS()); // -> myChangedList [ 1, 2, 3, 4 ]
The end result of calling push(4)
is a new list. If you want to make use of this list, you have to store it somewhere. In this example, we just want to print the JSON representation of the list, and as you can see, 4
is added to myChangedList
. You can also see that the contents of myList
haven't changed. Of course not—it's immutable!
Adding key-value pairs to maps
With maps, we use the...