ReactJS:如何更改对象数组中特定字段的值?

时间:2017-12-04 16:28:48

标签: javascript reactjs

constructor (props) {
    super(props)
    this.state = { items: this.props.items }
    // items props is: [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}]
}

onClick () {
    const myArray = this.state.items
    const ids = ['45', '73']
    ids.forEach((id, index) => {
        myArray.find(x => x.id === id).foo = index
    })
}

我需要将foo值更改为索引值。所以结果看起来应该是

myArray = [{'id':'73','foo': 1},{'id':'45','foo': 0}]

我认为有了这个,我确实得到了当前值,但改变其值的语法是错误的:

myArray.find(x => x.id === '45').foo = 'new'

我收到错误Uncaught TypeError: Cannot assign to read only property 'foo' of object '#<Object>'

1 个答案:

答案 0 :(得分:1)

您可以使用map更改所需的媒体资源:

&#13;
&#13;
const myArray = [{ id: '73', foo: 'bar' }, { id: '45', foo: 'new' }, { id: '46', foo: 'do not change me' }]

const ids = ['45', '73']

const newArr = myArray.map(item => {
  if (ids.indexOf(item.id) !== -1) {
    return {
      ...item,
      foo: 'newFooValue'
    }
  }
  
  return item
})

console.log(newArr)
&#13;
&#13;
&#13;

注意直接更改对象属性(例如myArray.find(x => x.id === '45').foo)并不是一个好习惯,这一点也很重要。

如果您items中有state,您可以通过以下方式进行简单的更改:

this.setState(prevState => ({
   items: prevState.items.map(/* same code as in the snippet above */),
}))