2

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.

3
  • Your original code is missing a {... Commented Feb 8, 2017 at 18:11
  • @Aaron not only {, missing the , also in object data Commented Feb 8, 2017 at 18:12
  • Right I have updated the code. Commented Feb 8, 2017 at 18:25

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

@DiegoUnanue codepen saved when I didn't want it to I changed it back should be good now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.