Created
January 30, 2018 17:03
-
-
Save Cotel/76fe984313166dab855720e8731694d8 to your computer and use it in GitHub Desktop.
An example of an immutable transformation of a deep object.
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
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