Skip to content
Advertisement

ReactJS Loop thru state array of object and add new field

I am learning reactjs and got an array of json object. I want to loop thru each record in the array, read the id and add/set a new field with a string value. When the looping is done, I will set the state to save the state collection. So far no luck in getting this to work.

Any help is greatly appreciated.

const records = this.state.OriginalRecords
let record = {}
records.map(m => (function(m) {
    // get the record for each record to update
    record = this.state.OriginalRecords.find(record => record.id === m.id)
    // add and set the record new field
    record['newField'] = 'Test'
  }
))

this.setState({OriginalRecords: records, mappingDateDone: true})

My goal is every record in OrginalRecords has a new json field called newField = ‘Test’.

Thanks

Advertisement

Answer

just do it like this using map function

const records = this.state.OriginalRecords

const newRecords = records.map(item =>  {
    return {...item , newField : 'Test'}
}); 

this.setState({OriginalRecords: newRecords, mappingDateDone: true})

Advertisement