I'm looking for a pure function, to modify my immutable state object. The original state given as parameter must stay untouched. This is especially useful when working with frameworks like Redux and makes working with immutable object in javascript much easier. Especially since working with the object spread operator using Babel is already possible.
I did not found anything better than first copy the object, and than assign/delete the property I want like this:
function updateState(state, item) {
newState = {...state};
newState[item.id] = item;
return newState;
}
function deleteProperty(state, id) {
var newState = {...state};
delete newState[id];
return newState;
}
I feel like it could be shorter
Try:
And test:
In a Map Function
To do this process within a map function (remove an attribute and add a new attribute on each object), given an array of objects -
Delete the attribute
keyToDelete
, and add a new keynewKey
with the value"someVar"
.Updating the array to
See this great post for more information on the deletion method.
Instead of writing boilerplate code (as answered above:
(({[id]: deleted, ...state}) => state)(state)
) which is hard to read, you could use some library to do the same:For example:
It's also supports any nested updates:
Removing item from an array, just use filter ;)
Actions on state, where state is considered immutable.
Adding or Updating the value of a property:
Deleting a property
An ES6 solution, that has a bit more support is
Object.assign
: