When working with plain JavaScript objects it's easy to change a deeply nested object property:
people.Thomas.nickname = "Mr. T";
But with Immutable I have to go through each property's ancestors before I have a new people object:
var thomas = peopleImmutable.get("Thomas");
var newThomas = thomas.set("nickname", "Mr .T");
peopleImmutable = peopleImmutable.set("Thomas", newThomas);
Is there a more elegant way to write this?
slice, from, map and filter are immutable because it creates a new array without mutating the original array. Object method which are immutable are object. assign. To make objects and arrays immutable you can use some techniques in JavaScript and create new values without modifying the original content.
To make an object immutable, recursively freeze each property which is of type object (deep freeze). Use the pattern on a case-by-case basis based on your design when you know the object contains no cycles in the reference graph, otherwise an endless loop will be triggered.
Set provides a range of methods not available to other Immutable objects that can be used to manipulate data in ways that a standard Immutable merge() cannot accomplish. These include Union , Intersect and Subtract . These operations are covered in the next Immutable. js tutorial on Sets.
Arrays and Objects Are MutableArrays and objects are not immutable in JavaScript because they can indeed change their value over time.
Maps in Immutable have a setIn method that makes it easy to set deep values:
peopleImmutable = peopleImmutable.setIn(["Thomas", "nickname"], "Mr. T");
Or, using split
to generate the array:
peopleImmutable = peopleImmutable.setIn("Thomas.nickname".split("."), "Mr. T");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With