Remove a property in an object immutably
How about using destructuring assignment syntax?
const original = { foo: 'bar', stack: 'overflow',};// If the name of the property to remove is constantconst { stack, ...withoutFirst } = original;console.log(withoutFirst); // Will be { "foo": "bar" }// If the name of the property to remove is from a variableconst key = 'stack'const { [key]: value, ...withoutSecond } = original;console.log(withoutSecond); // Will be { "foo": "bar" }// To do a deep removal with property names from variablesconst deep = { foo: 'bar', c: { x: 1, y: 2 }};const parentKey = 'c';const childKey = 'y';// Remove the 'c' element from originalconst { [parentKey]: parentValue, ...noChild } = deep;// Remove the 'y' from the 'c' elementconst { [childKey]: removedValue, ...childWithout } = parentValue;// Merge back togetherconst withoutThird = { ...noChild, [parentKey]: childWithout };console.log(withoutThird); // Will be { "foo": "bar", "c": { "x": 1 } }
I find ES5 array methods like filter
, map
and reduce
useful because they always return new arrays or objects. In this case I'd use Object.keys
to iterate over the object, and Array#reduce
to turn it back into an object.
return Object.assign({}, state, { c: Object.keys(state.c).reduce((result, key) => { if (key !== 'y') { result[key] = state.c[key]; } return result; }, {})});
You can use _.omit(object, [paths])
from lodash library
path can be nested for example: _.omit(object, ['key1.key2.key3'])