Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change property in array with Spread Operator returns object instead of array

I want to change the property of an object similar to this, this is a simplified object with a few properties of the original:

 state = {
    pivotComuns: [
      {
        id: 1,
        enabled : true
      },
      {
      id: 2,
      enabled : true
     }
   ],
   otherProperties : "otherProperties"
 }

I'm changing the state of enabled like this:

 state = {
            ...state,
            pivotColumns: {
              ...state.pivotColumns,
              [2]: {
                ...state.pivotColumns[2], enabled: !state.pivotColumns[2].enabled
              }
            }
          }

It works, but instead of return an array like I is the pivotComuns property it returns an object, "notice that I change [] for {}":

state = {
        pivotComuns: {
          {
            id: 1
            enabled : true
          },
          {
          id: 2,
          enabled : true
         }
       },
       otherProperties : "otherProperties"
     }

What I'm doing wrong, I need to keep that property an array.

like image 245
Diego Unanue Avatar asked Jan 24 '26 16:01

Diego Unanue


1 Answers

Very late post, but for future reference, you could do the following:

state = {
   ...state,
   pivotColumns: state.pivotColumns.map(pc => 
    pc.id === 2 ? {...pc, enabled:!pc.enabled} : pc
  )
}

The advantage is that you will not change the object referenced in the "old array", you will instead insert a new object in its place. So if you would like to go back and forth in the state you can now do so.

example: https://codepen.io/anon/pen/JyXqRe?editors=1111

like image 190
Erik Hålenius Avatar answered Jan 27 '26 04:01

Erik Hålenius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!