javascript - Remove value from object without mutating it -


what's , short way remove value object @ specific key without mutating original object?

i'd 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 lot of immutability libraries such tasks, i'd away without library. this, requirement have easy , short way can used throughout code, without abstracting method away utility function.

e.g. adding value following:

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

this quite short, easy remember , doesn't need utility function.

is there removing value? es6 welcome.

thank much!

update:

you remove property object tricky destructuring assignment:

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

though, if property name want remove static, remove simple one-liner:

let {lastname, ...o2} = o 

the easiest way to or clone object before mutating it:

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

alternatively use omit function lodash utility library:

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

it's available part of lodash package, or standalone lodash.omit package.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -