简体   繁体   English

如何在Immutable.js中设置深层嵌套的值?

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

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,我必须在拥有一个新的人物对象之前浏览每个属性的祖先:

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: Immutable中的地图有一个setIn方法 ,可以轻松设置深度值:

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

Or, using split to generate the array: 或者,使用split生成数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM