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

I need to change foo value to index value. So the result should look like

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

I think with this, I do get the current value, but the syntax is wrong to change its value:

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

I do get the error Uncaught TypeError: Cannot assign to read only property 'foo' of object '#<Object>'

5
  • No thats fine... Commented Dec 4, 2017 at 16:32
  • Works fine in the console. Commented Dec 4, 2017 at 16:32
  • The problem must be elsewhere, this demo in react works just fine. Commented Dec 4, 2017 at 16:56
  • @Ted: I'm setting the items state via props: this.state = { items: this.props.items } because I'll modify items as shown in the post. But with that I do get the error Uncaught TypeError: Cannot assign to read only property 'foo' of object '#<Object>' - also for your code. Commented Dec 4, 2017 at 17:11
  • @user3142695, then without seeing the code, I would suggest deep cloning the array, modifying the value in the clone, and setting state with the cloned array Commented Dec 4, 2017 at 17:16

1 Answer 1

2

You can use map to change the property you want:

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)

It's also important to note that change object properties directly (such as myArray.find(x => x.id === '45').foo) is not a good practice though.

In case itemsis in you state, you can simple change it by:

this.setState(prevState => ({
   items: prevState.items.map(/* same code as in the snippet above */),
}))
Sign up to request clarification or add additional context in comments.

2 Comments

That sounds great. Is it possible to modify multiple objects? I've updated the post. Please have a look at it. I need to change foo value of each object with the ID of the ids-array. Maybe I can avoid the forEach-loop? Maybe I can use indexOf inside of map?
@user3142695 sure you can :) I've just updated my answer. Hope that helps now :)

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.