Skip to content

Instantly share code, notes, and snippets.

View elliotlarson's full-sized avatar

Elliot Larson elliotlarson

View GitHub Profile
const characters = ["Walter", "Jeffrey", "Donald"];
const oldName = "Jeffrey";
const newName = "The Dude";
const newCharacters = { ...characters };
newCharacters[maude.id] = maude;
const newCharacters = Object.assign(characters, { [maude.id]: maude });
const newCharacters = { ...characters, [maude.id]: maude };
const characters = {
1: { id: 1, firstName: "Jeffrey", lastName: "Lebowski" },
2: { id: 2, firstName: "Walter", lastName: "Sobchak" },
3: { id: 3, firstName: "Donald", lastName: "Kerabatsos" }
};
const maude = { id: 4, firstName: "Maude", lastName: "Lebowski" };
// Adding Maude after Jeffrey at index 2
const newCharacters = [...characters];
newCharacters.splice(2, 0, maude);
// => ["Walter", "Jeffrey", "Maude", "Donald"]
// Creates a new array including the new item, turns it into a Set,
// which removes duplicates, and then turns it back to an array
const newCharacters = [...new Set([...characters, "Donald"])];
// Since "Donald" is a non-unique item, newCharacters will be:
// => ["Walter", "Jeffrey", "Donald"]
// creating a copy with `slice`
const newCharacters = characters.slice();
// you could also just copy with the spread
// const newCharacters = […characters];
newCharacters.push(maude);
const newCharacters = characters.concat(maude);
const newCharacters = [...characters, maude];