Monday, May 20, 2024
167
rated 0 times [  170] [ 3]  / answers: 1 / hits: 22283  / 8 Years ago, wed, july 27, 2016, 12:00:00

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?


More From » immutable.js

 Answers
34

This should work



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


References:




[#61241] Saturday, July 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anthonyw

Total Points: 589
Total Questions: 117
Total Answers: 117

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;