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

戏子无情 提交于 2019-12-02 22:45:38

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

How about immutability-helper? Works very well. You're looking for the $merge command I think.

@FellowStranger: I have one (and only one) section of my redux state that is an array of objects. I use the index in the reducer to update the correct entry:

case EMIT_DATA_TYPE_SELECT_CHANGE:
  return state.map( (sigmap, index) => {
    if ( index !== action.payload.index ) {
      return sigmap;
    } else {
      return update(sigmap, {$merge: {
        data_type: action.payload.value
      }})
    }
})

Frankly, this is kind of greasy, and I intend to change that part of my state object, but it does work... It doesn't sound like you're using redux but the tactic should be similar.

Instead of storing your values in an array, I strongly suggest using an object instead so you can easily specify which element you want to update. In the example below the key is the fieldName but it can be any unique identifier:

var fields = {
    title: {
        valid: false
    },
    description: {
        valid: true
    }
}

then you can use immutability-helper's update function:

var newFields = update(fields, {title: {valid: {$set: true}}})

Here is a sample example - ES6

The left is the code, and the right is the output

Here is the code below

const data = [
    { fieldName: 'title', valid: false }, 
    { fieldName: 'description', valid: true },
    { fieldName: 'cityId', valid: false }, // old data
    { fieldName: 'hostDescription', valid: false },
]

const newData = data.map(obj => {
  if(obj.fieldName === 'cityId') // check if fieldName equals to cityId
     return {
       ...obj,
       valid: true,
       description: 'You can also add more values here' // Example of data extra fields
     }
  return obj
});

const result = { data: newData }; 

console.log(result);

this.setState({ data: newData });

Hope this helps, Happy Coding!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!