Remove value from object without mutation

amann picture amann · Oct 10, 2015 · Viewed 73.6k times · Source

What's a good and short way to remove a value from an object at a specific key without mutating the original object?

I'd like to do something like:

let o = {firstname: 'Jane', lastname: 'Doe'};
let o2 = doSomething(o, 'lastname');
console.log(o.lastname); // 'Doe'
console.log(o2.lastname); // undefined

I know there are a lot of immutability libraries for such tasks, but I'd like to get away without a library. But to do this, a requirement would be to have an easy and short way that can be used throughout the code, without abstracting the method away as a utility function.

E.g. for adding a value I do the following:

let o2 = {...o1, age: 31};

This is quite short, easy to remember and doesn't need a utility function.

Is there something like this for removing a value? ES6 is very welcome.

Thank you very much!

Answer

Leonid Beschastny picture Leonid Beschastny · Oct 10, 2015

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.