如何在Immutable.js中设置深层嵌套的值? [英] How can I set a deeply nested value in Immutable.js?

查看:88
本文介绍了如何在Immutable.js中设置深层嵌套的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用纯JavaScript对象时,很容易更改深度嵌套的对象属性:

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?

推荐答案

Immutable中的地图具有 setIn方法使设置深度值变得容易:

Maps in Immutable have a setIn method that makes it easy to set deep values:

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

或者,使用split生成数组:

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

这篇关于如何在Immutable.js中设置深层嵌套的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆