javascript - 更新数组中的特定对象

标签 javascript svelte

我正在用 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/

相关文章:

svelte - 创建带参数的派生函数

slim : change variable value inside html block

javascript - Ext JS 中TreeStore 不能实现filterBy 方法吗?

php - 有什么方法可以将值从 JavaScript 发送到 CodeIgniter 中的 Controller 吗?

javascript - 对象有值但说大小为 0 javascript

svelte - 将插槽 Prop 绑定(bind)到插槽的父组件 Prop

javascript - nodeJS和 Electron 之间的区别

javascript - D3 监听 "end"转换事件

javascript - Array 中时间序列对象的移动平均值

javascript - supabaseUrl 是必需的 sveltekit