Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a deeply nested value in Immutable.js?

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?

like image 886
Matt Zeunert Avatar asked Sep 02 '15 10:09

Matt Zeunert


People also ask

What is used to create an immutable variable in JavaScript?

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.

How can I create immutable property in a JavaScript object?

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.

Are sets immutable in JavaScript?

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.

Are object values immutable?

Arrays and Objects Are MutableArrays and objects are not immutable in JavaScript because they can indeed change their value over time.


1 Answers

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");
like image 126
Matt Zeunert Avatar answered Oct 22 '22 21:10

Matt Zeunert