我正在用 Svelte 编写 SPA。现在,我对 ES6 的概念还很陌生,所以我很难理解一些基本概念。
我有一家商店:
import { writable } from "svelte/store";
function selectedOptions() {
const selection = writable([
{
id: 1,
title: "Title 1",
selections: []
},
{
id: 2,
title: "Title 2",
selections: []
},
{
id: 3,
title: "Title 3",
selections: []
},
{
id: 4,
title: "Title 4",
selections: []
},
{
id: 5,
title: "Title 5",
selections: []
},
{
id: 6,
title: "Title 6",
selections: []
}
]);
return {
subscribe: selection.subscribe,
updateSelection: item => {
selection.update((items) => {
//I want to update the object with the same id as the object
//I'm passing in to the method.
});
};
}
}
export default selectedOptions();
在我的组件中,我想传递一个对象并使用提供的值更新数组中的相应对象:
function handleChange(e) {
selectedOptions.updateSelection({
id: 1, title: "Title 1", selections: ["Option 1, Option 2"]
});
}
如何用新对象“替换”现有对象,从而触发订阅商店的所有组件的更新?
最佳答案
使用展开语法复制所有原始键,然后添加要修改的键:
selection.update(items => {
return {
...items,
[item.id]: item
}
});
关于javascript - 更新数组中的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58163174/