-1

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

Jonas
  • 405
  • 3
  • 7
  • 18

3 Answers3

1

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.

leonardfactory
  • 3,353
  • 1
  • 18
  • 25
0

Maybe try this

const newState = this.state.cartItems.map(item => {
  item.quantity = 0;

  return item;
});

this.setState({cartItems: newState});
Aaron
  • 2,364
  • 2
  • 31
  • 56
0
this.state= {
  cartItems:[
    {name:'item1',price:'$23'},
    {name:'item2',price:'$26'},
    {name:'item3',price:'$24'},
  ]
}
updateCartItems=()=>{ 
   var cartItems = this.state.cartItems.map((item)=>{
      return {...item,quantity:0}
   })
   this.setState({cartItems})
}
Sachin
  • 911
  • 8
  • 12