Immutable.js在嵌套对象中推入数组 [英] Immutable.js Push into array in nested object

查看:102
本文介绍了Immutable.js在嵌套对象中推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个对象:

const object = {
  'foo': {
    'bar': [1, 2, 3]
  }
}

我需要将 4 推送到 object.foo.bar 数组。

I need to push 4 to object.foo.bar array.

现在我这样做:

const initialState = Immutable.fromJS(object)
const newState = initialState.setIn(
  ['foo', 'bar', object.foo.bar.length],
  4
)
console.log(newState.toJS())

但我不是真的喜欢它,因为我需要在路径中使用 object.foo.bar.length 。在我的真实示例中,对象嵌套得更深,并且获取数组的长度看起来非常难看。还有另一个更方便的方法吗?

But I don't really like it, since I need to use object.foo.bar.length in the path. In my real example object is nested much deeper, and getting array's length looks very ugly. Is there another, more convenient way?

推荐答案

这应该有效

initialState.updateIn(['foo', 'bar'], arr => arr.push(4))

参考文献:

  • https://immutable-js.github.io/immutable-js/docs/#/updateIn

这篇关于Immutable.js在嵌套对象中推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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