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

Javascriptimmutable.js

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt ZeunertView Question on Stackoverflow
Solution 1 - JavascriptMatt ZeunertView Answer on Stackoverflow