Joe Privett Joe Privett - 4 months ago 44
React JSX Question

React addons update - how to insert an object into an array of objects?

I have an array of objects represented by

. How do I insert a new object into this array at position
? This is what i have so far, but I am getting the error

Error: update(): expected target of $push to be an array; got [object

let newBlocks = update(this.state, {
blocks: {
[pos] : {$push: [obj]}
blocks: newBlocks


$push appends element(s) to the end of the array and you need $splice here:

  blocks: update(this.state.blocks, {$splice: [[pos, 0, obj]]})

will insert obj into this.state.blocks at index specified by pos (deleting 0 items first).splice works according to the spec:

startIndex: index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

so it will work fine as long as the startIndex is within the length of the array