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

谁都会走 提交于 2019-11-29 02:06:40

问题


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?


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


来源:https://stackoverflow.com/questions/32350575/how-can-i-set-a-deeply-nested-value-in-immutable-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!