Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

javascript - Remove value from object without mutation

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...