更新数组中的特定对象
Updating a specific object in an array
我正在用 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"]
});
}
如何用新对象“替换”现有对象,从而触发对订阅商店的所有组件的更新?
如果 id
匹配,您可以使用数组方法 map
并合并新旧对象,或者如果 id
则按原样 return 旧对象] 不匹配。
updateSelection: item => {
selection.update(items => {
return items.map(i => (i.id === item.id ? { ...i, ...item } : i));
});
};
使用传播语法复制所有原始密钥,然后添加您要修改的密钥:
selection.update(items => {
return {
...items,
[item.id]: item
}
});
我正在用 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"]
});
}
如何用新对象“替换”现有对象,从而触发对订阅商店的所有组件的更新?
如果 id
匹配,您可以使用数组方法 map
并合并新旧对象,或者如果 id
则按原样 return 旧对象] 不匹配。
updateSelection: item => {
selection.update(items => {
return items.map(i => (i.id === item.id ? { ...i, ...item } : i));
});
};
使用传播语法复制所有原始密钥,然后添加您要修改的密钥:
selection.update(items => {
return {
...items,
[item.id]: item
}
});