I was trying to replace a property of an Object in an array with the spread syntax like this:
const origArray = [
{
"uuid":"c752cf08-d142-42f8-b9df-b1e6c4e1fba6",
"name":"Team 1",
"players":[
"41ed7b28-5a52-48a3-8587-1355b40fc81f"
]
},
{
"uuid":"d46829db-f2c6-44a3-bd59-e18e2740c069",
"name":"Team 2",
"players":[
]
}
]
const doesNotWork = (prev) => [...prev, {...prev[match], name: e.target.value}]
const result1 = doesNotWork(origArray)
console.log(result1)
// # I know this works:
const doesWork = (prev) => {
let old = [...prev]
old.splice(match, 1, {...prev[match], name: e.target.value});
return old;
})
const result2 = doesNotWork(origArray)
console.log(result2)
I expect reslut1 to be like result2, but i seem to be wrong. I would like to write this in a singe line function and not with the workaround I have, if possible.
As you can see, i have found a work around, but just to make sure I fully understand the problem, it is not replacing the object because its assuming its a different one, right?