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 { uuid_2, ...remainingItems } = items;
items = remainingItems; // Update items to exclude the deleted item
console.log(uuid_2); // Log the deleted item
console.log(items); // Log the remaining items
// Modify item with id "uuid_3"
const modifyId = "uuid_3";
items = {
...items,
[modifyId]: { ...items[modifyId], title: "Updated Item 3" },
};
console.log(items); // Log the updated items
// add new item
const newItem = { id: "uuid_4", title: "Item 4" };
items = { ...items, [newItem.id]: newItem };
console.log(items);
// if items is immutable
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" },
};
// Immutable delete
const deleteId = "uuid_2";
// const { uuid_2, ...itemsAfterDelete } = items; // directly uses the property name uuid_2 to extract and remove it from the items object.
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