Skip to content

Instantly share code, notes, and snippets.

@dannyid
Last active February 10, 2017 07:58
Show Gist options
  • Save dannyid/b11c1820a2d741e00b4cc23d85b2dc49 to your computer and use it in GitHub Desktop.
Save dannyid/b11c1820a2d741e00b4cc23d85b2dc49 to your computer and use it in GitHub Desktop.
Updating Deep Immutable Object with ES6 Spread. From: https://github.com/sebmarkbage/ecmascript-rest-spread/blob/master/Spread.md

Updating Deep Immutable Object

let newVersion = {
  language: 'Default Language', // Set default for unspecified properties
  ...previousVersion,
  name: 'New Name', // Override the name property
  address: {
    ...previousVersion.address,
    zipCode: '99999' // Update nested zip code
  },
  items: [
    {title: 'New First Item'}, // Add an item to the beginning of items
    ...previousVersion.items,
    {title: 'New Last Item'} // Add an item to the end of items
  ],
  
};
@jonearley
Copy link

jonearley commented Dec 14, 2016

What if you wanted to update a title of an item from items?

items: [
    ...previousVersion.items,
    {title: 'Updated title'} // how would you update this?
  ]

@koestersc
Copy link

koestersc commented Dec 29, 2016

@jonearley what about a .map call on previousVersion.items ? If you find the item that you want to change, replace it with a new one, else just return each item.

e.g.
items: previousVersion.items.map((item) => (isItemToChange ? newItem : item));

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