Immutable.js Insert an array into a nested object

Suppose there is an object:

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

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

Now I am doing this:

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

But I do not really like this, since I need to use object.foo.bar.length in the path. In my real example, the object is nested much deeper, and the length of the array looks very ugly. Is there any other, more convenient way?

+14
javascript
source share
2 answers

This should work

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

Recommendations:

+31
source share

I use seamless-immutable , when I add a new element to an array of a nested object, I got this error:

The push method cannot be called in an immutable data structure.

My array still has a push method, but it does not work. Instead, the concat solution is used, more details on # 43 :

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

Hope this help!

+4
source share

All Articles