Tarion Tarion - 7 months ago 30
Javascript Question

What is the shortest way to modify immutable objects using Javascript es7 spread and destructuring operators

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 es7 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

Answer

Actions on state, where state is considered immutable.

Adding or Updating the value of a property:

// ES6:
function updateState(state, item) {
    return Object.assign({}, state, {[item.id]: item});
}

// ES7:
function updateState(state, item) {
  return {
     ...state,
     [item.id]: item
  };
}

Deleting a property

// ES6:
function deleteProperty(state, id) {
    var newState = Object.assign({}, state);
    delete newState[id];
    return newState; 
}

// ES7:
function deleteProperty(state, id) {
    let  {[id]: deleted, ...newState} = state;
    return newState;
}
// Or even shorter as helper function:
function deleteProperty({[id]: deleted, ...newState}, id) {
    return newState;
}