Reputation: 1180
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
Upvotes: 0
Views: 546
Reputation: 2363
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})
Upvotes: 2
Reputation: 3518
const records = this.state.OriginalRecords
const mappedRecords = records.map(m => (function(m) {
const item = this.state.OriginalRecords.find(record => record.id === m.id)
// add and set the record new field
item['newField'] = 'Test'
}
))
this.setState({OriginalRecords: mappedRecords, mappingDateDone: true})
Upvotes: 0