Skip to content

Instantly share code, notes, and snippets.

@elliotlarson
Created July 22, 2018 04:13
Show Gist options
  • Save elliotlarson/b96a4865aadfa0cb9a5bacb59de36249 to your computer and use it in GitHub Desktop.
Save elliotlarson/b96a4865aadfa0cb9a5bacb59de36249 to your computer and use it in GitHub Desktop.
const newCharacters = Object.assign(characters, { [maude.id]: maude });
@flamingbear
Copy link

I know this is two years ago. But this mutates characters.

> characters
{ '1': { id: 1, firstName: 'Jeffrey', lastName: 'Lebowski' },
  '2': { id: 2, firstName: 'Walter', lastName: 'Sobchak' },
  '3': { id: 3, firstName: 'Donald', lastName: 'Kerabatsos' } }
> const newCharacters = Object.assign(characters, { [maude.id]: maude });

const newCharacters = Object.assign(characters, { [maude.id]: maude });
undefined
> 
> characters
{ '1': { id: 1, firstName: 'Jeffrey', lastName: 'Lebowski' },
  '2': { id: 2, firstName: 'Walter', lastName: 'Sobchak' },
  '3': { id: 3, firstName: 'Donald', lastName: 'Kerabatsos' },
  '4': { id: 4, firstName: 'Maude', lastName: 'Lebowski' } }
> newCharacters
{ '1': { id: 1, firstName: 'Jeffrey', lastName: 'Lebowski' },
  '2': { id: 2, firstName: 'Walter', lastName: 'Sobchak' },
  '3': { id: 3, firstName: 'Donald', lastName: 'Kerabatsos' },
  '4': { id: 4, firstName: 'Maude', lastName: 'Lebowski' } }
> characters === newCharacters
true

You need to provide a new object to assign this to.
> const newCharacters2 = Object.assign({}, characters, { [maude.id]: maude });

> newCharacters2 === newCharacters
false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment