更新数组中的特定对象

时间:2019-09-30 07:18:15

标签: javascript svelte

我正在Svelte中编写SPA。现在,我对ES6的概念还很陌生,因此我难以理解som的基本概念。

我有一家商店:

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

如何用一个新对象“替换”一个现有对象,从而触发对预订该商店的所有组件的更新?

2 个答案:

答案 0 :(得分:1)

如果df <- data.frame( grade1 = sample(1:10), class = sample(c("maths", "english"), 10, replace = TRUE) ) df$grade1<-car::recode(df$grade1,"3=NA") # ungrouped, same SD regardless of group and NAs omitted in SD calculation, but this is not something I want. df$sd_grade1 <- sd(df$grade1, na.rm = TRUE) # grouped, but na.rm does not work here because "maths" contains one NA. df$sd_grp_grade1 <- ave(df$grade1, df$class, FUN = sd, na.rm = TRUE) 匹配,则可以使用数组方法map合并新对象和旧对象,或者如果id不匹配,则按原样返回旧对象。

id

答案 1 :(得分:1)

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

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