Home > Software engineering >  Set state to new object using previous state with matching values
Set state to new object using previous state with matching values

Time:06-10

I have state that contains an object that looks something like this

stateObject = {0: 400, 1: 500, 2: 600}

On componentWillUpdate my component rerenders and an extra component (column) is added in and carries over the 0 key index value (400).

I want to set the new state to look like the state down below, so that the original values are kept but are equal to the incremented index keys (this is so the newest column doesn't carry over the value 400 and the next column which was the original column has the correct value)

ex. 0: 400 would now equal to 1:400, 1:500 would now equal 2:500 etc. This would allow the correct columns to have the correct values that they need

newStateObject = {0: undefined, 1: 400, 2: 500, 3: 600}

What is the best way to approach this? I've tried using Object.assign to create a new object that matches this desired object structure and setting that to state but I can't get it to work.

Any help or advice is appreciated!

CodePudding user response:

Considering obj to be the previous state Object in the callback representation of this.setState(prevState => {}),the following should work.Note that i am not adding the {0:undefined} because that is redundant

const obj = {0: 400, 1: 500, 2: 600}
const keys = Object.keys(obj)
const incrementedArray = keys.map(key => ({[`${Number(key) 1}`]:obj[key]}))
const incrementedObject = incrementedArray.reduce((map,obj)=>({...map,...obj}),{})
console.log('incrementedObject',incrementedObject)

CodePudding user response:

Easiest would be if you store the state as an array. 0, 1, 2, 3 seem to be used as index anyway. When using an array you can prefix undefined easily.

// current state is [400, 500, 600]
//                    0    1    2
setState(state => [undefined, ...state])
// new state will be [undefined, 400, 500, 600]
//                        0       1    2    3
  • Related