[英]ReactJS Loop thru state array of object and add new field
I am learning reactjs and got an array of json object.我正在学习 reactjs 并获得了一组 json 对象。 I want to loop thru each record in the array, read the id and add/set a new field with a string value.
我想遍历数组中的每条记录,读取 id 并添加/设置一个带有字符串值的新字段。 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'.我的目标是 OrginalRecords 中的每条记录都有一个名为 newField = 'Test' 的新 json 字段。
Thanks谢谢
just do it like this using map function使用 map 函数就可以这样做
const records = this.state.OriginalRecords
const newRecords = records.map(item => {
return {...item , newField : 'Test'}
});
this.setState({OriginalRecords: newRecords, mappingDateDone: true})
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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.