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.
JavaScript
x
12
12
1
const records = this.state.OriginalRecords
2
let record = {}
3
records.map(m => (function(m) {
4
// get the record for each record to update
5
record = this.state.OriginalRecords.find(record => record.id === m.id)
6
// add and set the record new field
7
record['newField'] = 'Test'
8
}
9
))
10
11
this.setState({OriginalRecords: records, mappingDateDone: true})
12
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
JavaScript
1
9
1
const records = this.state.OriginalRecords
2
3
const newRecords = records.map(item => {
4
return {item , newField : 'Test'}
5
});
6
7
this.setState({OriginalRecords: newRecords, mappingDateDone: true})
8
9