小编典典

不可变地删除对象中的属性

all

我正在使用 Redux。在我的减速器中,我试图从这样的对象中删除一个属性:

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

我想拥有这样的东西而不必改变原始状态:

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

我试过了:

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

但由于某些原因,它会从两个州删除该属性。

可以帮我做吗?


阅读 58

收藏
2022-07-29

共1个答案

小编典典

使用解构赋值语法怎么样?

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 } }
2022-07-29