Remove a property in an object immutably

2019-03-07 21:00发布

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?

14条回答
我命由我不由天
2楼-- · 2019-03-07 21:34

That's because you are copying the value of state.c to the other object. And that value is a pointer to another javascript object. So, both of those pointers are pointing to the same object.

Try this:

let newState = Object.assign({}, state);
console.log(newState == state); // false
console.log(newState.c == state.c); // true
newState.c = Object.assign({}, state.c);
console.log(newState.c == state.c); // now it is false
delete newState.c.y;

You can also do a deep-copy of the object. See this question and you'll find what's best for you.

查看更多
甜甜的少女心
3楼-- · 2019-03-07 21:34

I use this pattern

const newState = Object.assign({}, state);
      delete newState.show;
      return newState;

but in book i saw another pattern

return Object.assign({}, state, { name: undefined } )
查看更多
登录 后发表回答