Remove a property in an object immutably Remove a property in an object immutably javascript javascript

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 } }