let items = {
"uuid-1": { id: "uuid-1", title: "Item 1" },
"uuid-2": { id: "uuid-2", title: "Item 2" },
"uuid-3": { id: "uuid-3", title: "Item 3" },
};
// Delete item with id "uuid-2"
const deleteId = "uuid-2";
const { [deleteId]: deletedItem, ...remainingItems } = items;
items = remainingItems; // Update items to exclude the deleted item
console.log(deletedItem); // Log the deleted item
console.log(items); // Log the remaining items
// modify item with id "uuid-3"
const modifieId = "uuid-3";
const updatedItem = { ...items[modifieId], title: "New item 3" };
items = { ...items, [modifieId]: updatedItem };
console.log(items);
// add new item
const newItem = { id: "uuid-4", title: "Item 4" };
items = { ...items, [newItem.id]: newItem };
console.log(items);
// if items is immutable
// Original items object
const items = {
"uuid-1": { id: "uuid-1", title: "Item 1" },
"uuid-2": { id: "uuid-2", title: "Item 2" },
"uuid-3": { id: "uuid-3", title: "Item 3" },
};
// Immutable delete
const deleteId = "uuid-2";
const { [deleteId]: deletedItem, ...itemsAfterDelete } = items;
// Immutable modify
const modifyId = "uuid-3";
const itemsAfterModify = {
...itemsAfterDelete,
[modifyId]: { ...itemsAfterDelete[modifyId], title: "New item 3" },
};
// Immutable add
const newItem = { id: "uuid-4", title: "Item 4" };
const itemsAfterAdd = { ...itemsAfterModify, [newItem.id]: newItem };
console.log(items); // Original items object remains unchanged
console.log(itemsAfterDelete); // Items after deletion
console.log(itemsAfterModify); // Items after modification
console.log(itemsAfterAdd); // Items after adding a new item