Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save odewahn/cfc17dd970450257ba918a2568a2e97b to your computer and use it in GitHub Desktop.
Save odewahn/cfc17dd970450257ba918a2568a2e97b to your computer and use it in GitHub Desktop.
// Based on https://dev.to/andyrewlee/cheat-sheet-for-updating-objects-and-arrays-in-react-state-48np
const DATA = [
{ id: 123, name: "bart" },
{ id: 256, name: "lisa" },
{ id: 344, name: "homer" },
{ id: 412, name: "marge" },
];
const addRecord = { id: 477, name: "frink" };
const updatedRecord = { id: 256, name: "barney" };
const removeRecord = { id: 123, name: "bart" };
// add an element
const add = [...DATA, addRecord];
console.log("Add", add);
// Remove from an array
const remove = DATA.filter((item) => item.id !== removeRecord.id);
console.log("Remove", remove);
// Find a person based on a hash and update the name
const idx = DATA.findIndex((item) => item.id == updatedRecord.id);
const replace = DATA.map((item, i) => (i == idx ? updatedRecord : item));
console.log("Replace", replace);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment