Created
April 6, 2022 11:43
-
-
Save odewahn/cfc17dd970450257ba918a2568a2e97b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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