私は 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
しかし、何らかの理由により、両方の状態からプロパティが削除されます。
それを手伝ってもらえますか?
ベストアンサー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 } }