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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:56:22  来源:igfitidea点击:

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

javascriptimmutable.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 splitto generate the array:

或者,split用于生成数组:

peopleImmutable = peopleImmutable.setIn("Thomas.nickname".split("."), "Mr. T");