Search code examples
javascriptimmutabilityredux

Remove a property in an object immutably


I am using Redux. In my reducer I'm trying to remove a property from an object like this:

const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}

And I want to have something like this without having to mutate the original state:

const newState = {
    a: '1',
    b: '2',
    c: {
       x: '42',
    },
}

I tried:

let newState = Object.assign({}, state);
delete newState.c.y

but for some reasons, it deletes the property from both states.

Could help me to do that?


Solution

  • How about using destructuring assignment syntax?

    const original = {
      foo: 'bar',
      stack: 'overflow',
    };
    
    // If the name of the property to remove is constant
    const { stack, ...withoutFirst } = original;
    console.log(withoutFirst); // Will be { "foo": "bar" }
    
    // If the name of the property to remove is from a variable
    const key = 'stack'
    const { [key]: value, ...withoutSecond } = original;
    console.log(withoutSecond); // Will be { "foo": "bar" }
    
    // To do a deep removal with property names from variables
    const deep = {
      foo: 'bar',
      c: {
       x: 1,
       y: 2
      }
    };
    
    const parentKey = 'c';
    const childKey = 'y';
    // Remove the 'c' element from original
    const { [parentKey]: parentValue, ...noChild } = deep;
    // Remove the 'y' from the 'c' element
    const { [childKey]: removedValue, ...childWithout } = parentValue;
    // Merge back together
    const withoutThird = { ...noChild, [parentKey]: childWithout };
    console.log(withoutThird); // Will be { "foo": "bar", "c": { "x": 1 } }