Prajna
Prajna

Reputation: 648

How do I update the state of a array element?

I have an array of below format

constructor(){
    super();
    this.state = {
    details: [ 
      {
        id: 1,
        class: '10',
        section: 'A',
        subject: 'Social',
        name: 'abc'
      },
      { 
        id: 2,
        class: '8',
        section: 'C',
        subject: 'Social',
        name: 'abc'
      },
      {
      id: 3,
      class: '9',
      section: 'A',
      subject: 'Social',
      name: 'abc'
      } 
    ]
}

I want to update each name in a loop. How can I update the state. I am trying with the below code.

this.state.details.map((item, key) => {
    this.setState({
       details.key.name: 'trial'
    })      
})

Upvotes: 1

Views: 38

Answers (1)

Paras Korat
Paras Korat

Reputation: 2065

You can do it like this.

 modifiedData = this.state.details.map((item, index) => { return { ...item, name: "trial" } })

Upvotes: 2

Related Questions