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?
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");
来源:https://stackoverflow.com/questions/32350575/how-can-i-set-a-deeply-nested-value-in-immutable-js