Asbestus Bonitas
Asbestus Bonitas

Reputation: 55

Updating a specific object in an array

I'm writing an SPA in Svelte. Now, I'm fairly new to the concepts of ES6 so I'm having difficulties wrapping my head around some basic concepts.

I have a store:

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();

In my component, I want to pass an object and update the corresponding object in my array with provided values:

function handleChange(e) {
    selectedOptions.updateSelection({
        id: 1, title: "Title 1", selections: ["Option 1, Option 2"]
    });
}

How do I "replace" an existing object with a new one thus triggering an update to all components that are subscribing to the store?

Upvotes: 2

Views: 166

Answers (2)

collardeau
collardeau

Reputation: 820

Use the spread syntax to copy all the original keys, then add the one you want to modify:

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

Upvotes: 4

Tholle
Tholle

Reputation: 112787

You could use the array method map and merge the new and old object if the id matches or just return the old object as-is if the id doesn't match.

updateSelection: item => {
  selection.update(items => {
    return items.map(i => (i.id === item.id ? { ...i, ...item } : i));
  });
};

Upvotes: 1

Related Questions