Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable.js Push into array in nested object

Assume there is an object:

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

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

Right now I'm doing it like this:

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

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?

like image 706
Alexandr Lazarev Avatar asked Jul 27 '16 10:07

Alexandr Lazarev


People also ask

Is array push immutable?

Immutable array operations. Array has several mutable operations - push, pop, splice, shift, unshift, reverse and sort. Using them is usually causing side effects and bugs that are hard to track. That's why it's important to use an immutable way.

Is JavaScript array immutable?

In JavaScript, only objects and arrays are mutable, not primitive values.

Is array splice immutable?

splice() is not immutable. It modifies the given array.

Is an array object immutable?

Strings and numbers are naturally immutable, but arrays and objects are not.


2 Answers

This should work

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

References:

  • https://immutable-js.github.io/immutable-js/docs/#/updateIn
like image 92
zerkms Avatar answered Oct 19 '22 00:10

zerkms


I'm using seamless-immutable, when I'm adding a new item to array of nested object, I got this error:

The push method cannot be invoked on an Immutable data structure.

My array still has push method, but it doesn't work. The solution is use concat instead, more details on #43:

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

Hope this help!

like image 33
Huy Nguyen Avatar answered Oct 19 '22 02:10

Huy Nguyen