0

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

2 Answers 2

2

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})

Sign up to request clarification or add additional context in comments.

Comments

0
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})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.