Good way to update each item in an array inside a store

1.3k views Asked by At

I have an array of objects inside my data store in Svelte, I would like to update one property in every single object in the array, i.e. I want to update the author property inside the array in my store to the current user name, this is what I'm currently doing:

let tempArray = $myReviewDataStore;
for(var i=0; i < tempArray.length; i++){
    tempArray[i].author = username;
}
myReviewDataStore.update(data =>{
    return tempArray;
})

There must be a better way to do this, right?

Thanks!

2

There are 2 answers

0
grohjy On

This is just a shorter way to do it:

$myReviewDataStore = $myReviewDataStore.map(
 obj => ({...obj, author: username})
);
0
Gh05d On

Hm, I guess you don't really need the first part of your logic, as the data prop contains the store value:

update is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.

So you could shorten it this instead:

myReviewDataStore.update(data => data.map(state => ({...state, author: username }) ));