Update one of the objects in array, in an immutable way

You can use map to iterate the data and check for the fieldName, if fieldName is cityId then you need to change the value and return a new object otherwise just return the same object.

Write it like this:

var data = [
    {fieldName: 'title', valid: false}, 
    {fieldName: 'description', valid: true},
    {fieldName: 'cityId', valid: false},
    {fieldName: 'hostDescription', valid: false},

var newData = data.map(el => {
                  if(el.fieldName == 'cityId')
                     return Object.assign({}, el, {valid:true})
                  return el

this.setState({ data: newData }); 

Leave a Comment