Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更新数组中的特定对象_Javascript_Svelte - Fatal编程技术网

Javascript 更新数组中的特定对象

Javascript 更新数组中的特定对象,javascript,svelte,Javascript,Svelte,我在写一个苗条的水疗。现在,我对ES6的概念还比较陌生,所以我很难理解一些基本概念 我有一家商店: import { writable } from "svelte/store"; function selectedOptions() { const selection = writable([ { id: 1, title: "Title 1", selec

我在写一个苗条的水疗。现在,我对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
匹配,则可以使用数组方法合并新对象和旧对象;如果
id
不匹配,则只返回旧对象

updateSelection:item=>{
选择。更新(项目=>{
返回items.map(i=>(i.id===item.id?{…i,…item}:i));
});
};

使用排列语法复制所有原始密钥,然后添加要修改的密钥:

selection.update(items => {
  return {
     ...items,
     [item.id]: item
  }
});