TransWikia.com

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

Stack Overflow Asked by Hank on February 14, 2021

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 Answers

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

Answered by Gh05d on February 14, 2021

This is just a shorter way to do it:

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

Answered by grohjy on February 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP