Skip to content

Instantly share code, notes, and snippets.

@Cotel
Created January 30, 2018 17:03
Show Gist options
  • Save Cotel/76fe984313166dab855720e8731694d8 to your computer and use it in GitHub Desktop.
Save Cotel/76fe984313166dab855720e8731694d8 to your computer and use it in GitHub Desktop.
An example of an immutable transformation of a deep object.
const restaurant = {
clientRequests: {
"1": {
"drinks": [
{id: 3, name: "Beer", quantity: 4}
]
},
"2": {
"appetizers": [
{id: 1, name: "Onion rings", quantity: 2},
{id: 2, name: "Cheese and bacon fries", quantity: 1}
],
"drinks": [
{id: 3, name: "Beer", quantity: 3}
]
}
},
isOpen: true,
totalTables: 7
}
// We want to add one more ration of fries for table number 2
const alteredRestaurant = {...restaurant,
clientRequests: {...restaurant.clientRequests,
"2": { ...restaurant.clientRequests["2"],
"appetizers": restaurant.clientRequests["2"]["appetizers"].map(appetizer =>
(appetizer["id"] === 2) ? {...appetizer, quantity: appetizer.quantity+1} : appetizer)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment