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?
Solution 1:
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");