You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
update array with objects using Array.prototype.slice
varstate=[{name: "Goran"},{name: "Peter"}]// you can use es6 Array.prototype.findIndex to find index of the object// let index = state.findIndex(({name}) => name === "Peter");varindex=1;varfield='name';varvalue='Zika';varnewState=[
...state.slice(0,index),{
...state[index],[field]: value},
...state.slice(index+1)];console.log(newState);/* [ {name: "Goran"}, {name: "Zika"} ]*/
Hi @Jonarod! that happens because you are using objects, so the reference to the objects inside the newState array is the same located in state array.
So when you did
var newState = [
...state.slice(0)
]
You are only changing the reference of the array but the reference in objects still remaining the same in both.
That is the reason why in the above example he needs to do this:
{
...state[index],
[field]: value
}
You can see the spread operator in state[index] in order to get a shallow copy of the current object in the state array giving with that a new reference in the newState array.
Hi @Jonarod! that happens because you are using objects, so the reference to the objects inside the newState array is the same located in state array.
So when you did
You are only changing the reference of the array but the reference in objects still remaining the same in both.
That is the reason why in the above example he needs to do this:
You can see the spread operator in state[index] in order to get a shallow copy of the current object in the state array giving with that a new reference in the newState array.