Search code examples
javascriptreactjsecmascript-6react-reduxecmascript-2016

How to push new value into array of object in React


I think it might be silly question to ask but trust I am new to React . I am trying to push new key and value to array of object but I am not able to do it . Could someone please help me how to achieve my goal. Thanks

Code

this.state= {
cartItems=[
{name:'item1',price:'$23'},
{name:'item2',price:'$26'},
{name:'item3',price:'$24'},
]

I want to add new value like quantity:0 in the end of array of object. Please help me


Solution

  • If you want to update state adding a property to each object, you should just use setState in combination with map. Array.prototype.map allows you to transform each object, like this:

    this.setState(state => {
      cartItems: state.cartItems.map(cartItem => ({ 
        ...cartItem, // Keep all old properties
        quantity: 0 // Add quantity
      })
    })
    

    You should do this only if you're calling setState after the initializer. If you need to modifiy the data right when assigning to this.state, just map the array directly.