简体   繁体   中英

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.

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

I don't believe you can use the spread operator in such a way and in fact wouldn't recommend it if you could because it creates very hard to read code. There is a much simpler solution that I use on a daily basis when it comes to updating a key/value on an object where the value is an array:

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

var clonedPivotColumns = state.pivotColumns.slice();

clonedPivotColumns[1].enabled = !state.pivotColumns[1].enabled;

state = {
   ...state,
   pivotColumns: clonedPivotColumns
 }

this will get you the right results and will not cause any mutations.

working pen http://codepen.io/finalfreq/pen/ggdJgQ?editors=1111

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM