我正在使用Redux.在我的reducer中,我试图从像这样的对象中删除一个属性:
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
但由于某些原因,它会删除两个州的财产.
可以帮我这么做吗?
如何使用解构赋值语法?
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 } }
我觉得ES5阵列的方法,如filter
,map
和reduce
有用的,因为他们总是返回新的数组或对象.在这种情况下,我将使用Object.keys
迭代对象,并将Array#reduce
其转回对象.
return Object.assign({}, state, { c: Object.keys(state.c).reduce((result, key) => { if (key !== 'y') { result[key] = state.c[key]; } return result; }, {}) });
您可以使用_.omit(object, [paths])
从lodash库
path可以嵌套,例如: _.omit(object, ['key1.key2.key3'])
只需使用ES6对象解构功能
const state = {
c: {
x: '42',
y: '43'
},
}
const { c: { y, ...c } } = state // generates a new 'c' without 'y'
console.log({...state, c }) // put the new c on a new state
那是因为你正在将值复制state.c
到另一个对象.该值是指向另一个javascript对象的指针.因此,这两个指针都指向同一个对象.
试试这个:
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;
您还可以对该对象执行深层复制.看到这个问题,你会发现什么是最适合你的.
这个怎么样:
function removeByKey (myObj, deleteKey) { return Object.keys(myObj) .filter(key => key !== deleteKey) .reduce((result, current) => { result[current] = myObj[current]; return result; }, {}); }
它过滤应删除的密钥,然后从剩余的密钥和初始对象构建一个新对象.想法是从Tyler McGinnes真棒反应计划中偷走的.
JSBin
function dissoc(key, obj) { let copy = Object.assign({}, obj) delete copy[key] return copy }
此外,如果要寻找功能性编程工具包,请查看Ramda.
在您的情况下,您可以使用Immutability助手来取消设置属性:
import update from 'immutability-helper'; const updatedState = update(state, { c: { $unset: ['y'] } });
使用Immutable.js很容易:
const newState = state.deleteIn(['c', 'y']);
deleteIn()的描述