Immutability and you: Part 3
Alain D'Ettorre
Posted on July 9, 2020
In this article we're going to see how you can change an object immutably
Add new properties
const programmer = {
sleeplessHours: 5347,
};
const hacker = {
...programmer,
nickname: 'h4ck3r_l1f3',
};
/*
hacker = {
sleeplessHours: 5347,
nickname: 'h4ck3r_l1f3',
};
*/
Overwrite existing properties
const twoYearsOldKid = {
name: 'Come up with a name yourself',
someOtherProp: 42,
age: 2,
};
const threeYearsOldKid = {
...twoYearsOldKid,
age: 3,
};
/*
threeYearsOldKid = {
name: 'Come up with a name yourself',
someOtherProp: 42,
age: 3,
};
*/
Remove a property
const userData = {
username: 'john.doe',
someSecretData: 'I like cats',
comments: 1234,
averageRating: 4.3,
};
const { someSecretData, ...filteredUserData } = userData;
/*
filteredUserData = {
username: 'john.doe',
comments: 1234,
averageRating: 4.3,
};
*/
Putting it all together
Let's say we have this recipe object
const recipe = {
ingredients: [
'bread',
'meat',
'salad',
'fries',
'gravy',
],
price: 5.90,
steps: [
'Cook the meat',
'Fry the fries',
'Slice the bread',
'Slice the salad',
'Assemble',
],
};
And we want to add a new ingredient and a new step at the same time. Here's how to do it
const betterRecipe = {
...recipe,
ingredients: [
...recipe.ingredients,
'secret sauce',
],
steps: [
...recipe.steps.slice(0, recipe.steps.length - 1),
'Add the secret sauce',
...recipe.steps.slice(recipe.steps.length - 1),
],
};
/*
betterRecipe = {
ingredients: [
'bread',
'meat',
'salad',
'fries',
'gravy',
'secret sauce',
],
price: 5.90,
steps: [
'Cook the meat',
'Fry the fries',
'Slice the bread',
'Slice the salad',
'Add the secret sauce',
'Assemble',
],
};
*/
Notice that the new ingredient was added as the last item of the ingredients
property, but the new step was added as the second-last item of the steps
property (before "Assemble", the last one). This is done by "splitting" the array in two parts (the last step on the right and all the others on the left) and inserting the new step right inside the split.
If you liked this series please leave some feedback. See you next time!
Photo by Salmen Bejaoui on Unsplash
Posted on July 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.