We only know the index, where we want to edit the object in the array
Given a knownIndex
this.setState({
array:
[ ...this.state.array.slice (0, knownIndex) // <-- items up to the index
, someUpdate(this.state.array[knownIndex])) // <-- updated object
, ...this.state.array.slice (knownIndex + 1) // <-- items after the index
]
})
Another way you could do it is using the Array .map function. Let's also make it a generic function
const updateAtIndex = (xs, i, f) =>
xs .map ((x, j) => i === j ? f (x) : x)
In your component, you can use it like this
this.setState ({
array: updateAtIndex (this.state.array, knownIndex, f)
})
Where f is some function to update the object, for example
// returns a new object with the n property doubled
const f = obj =>
({ n: obj.n * 2 })
When writing generic functions, I like to make them a little more robust. If you use this technique in your program, I would recommend a few changes to the functions above. These changes communicate the parameter types more effectively and allow the reader to better infer the functions return type.
const identity = x =>
x
const updateAtIndex = (xs = [], i = 0, f = identity) =>
xs .map ((x, j) => i === j ? f (x) : x)
const f = ({ n = 0 }) =>
({ n: n * 2 })