Javascript 如何在 Immutable.js 中设置深度嵌套的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32350575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set a deeply nested value in Immutable.js?
提问by Matt Zeunert
When working with plain JavaScript objects it's easy to change a deeply nested object property:
使用纯 JavaScript 对象时,很容易更改深度嵌套的对象属性:
people.Thomas.nickname = "Mr. T";
But with Immutable I have to go through each property's ancestors before I have a new people object:
但是对于 Immutable,在我拥有一个新的 people 对象之前,我必须通过每个属性的祖先:
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?
有没有更优雅的方式来写这个?
回答by Matt Zeunert
Maps in Immutable have a setIn methodthat makes it easy to set deep values:
Immutable 中的Map有一个setIn 方法,可以轻松设置深层值:
peopleImmutable = peopleImmutable.setIn(["Thomas", "nickname"], "Mr. T");
Or, using split
to generate the array:
或者,split
用于生成数组:
peopleImmutable = peopleImmutable.setIn("Thomas.nickname".split("."), "Mr. T");