Remove value from object without mutation Remove value from object without mutation javascript javascript

Remove value from object without mutation


Update:

You could remove a property from an object with a tricky Destructuring assignment:

const doSomething = (obj, prop) => {  let {[prop]: omit, ...res} = obj  return res}

Though, if property name you want to remove is static, then you could remove it with a simple one-liner:

let {lastname, ...o2} = o

The easiest way is simply to Or you could clone your object before mutating it:

const doSomething = (obj, prop) => {  let res = Object.assign({}, obj)  delete res[prop]  return res}

Alternatively you could use omit function from lodash utility library:

let o2 = _.omit(o, 'lastname')

It's available as a part of lodash package, or as a standalone lodash.omit package.


With ES7 object destructuring:

const myObject = {  a: 1,  b: 2,  c: 3};const { a, ...noA } = myObject;console.log(noA); // => { b: 2, c: 3 }


one line solution

const removeKey = (key, {[key]: _, ...rest}) => rest;

Explanations:

This is a generic arrow function to remove a specific key. The first argument is the name of the key to remove, the second is the object from where you want to remove the key. Note that by restructuring it, we generate the curated result, then return it.

Example:

let example = {   first:"frefrze",  second:"gergerge",  third: "gfgfg"}console.log(removeKey('third', example))/*Object {  first: "frefrze",  second: "gergerge"}*/