I have a flat JS object:
{a: 1, b: 2, c: 3, ..., z:26}
I want to clone the object except for one element:
{a: 1, c: 3, ..., z:26}
What's the easiest way to do this (preferring to use es6/7 if possible)?
I have a flat JS object:
{a: 1, b: 2, c: 3, ..., z:26}
I want to clone the object except for one element:
{a: 1, c: 3, ..., z:26}
What's the easiest way to do this (preferring to use es6/7 if possible)?
If you're dealing with a huge variable, you don't want to copy it and then delete it, as this would be inefficient.
A simple for-loop with a hasOwnProperty check should work, and it is much more adaptable to future needs :
If you use Babel you can use the following syntax to copy property b from x into variable b and then copy rest of properties into variable y:
and it will be transpiled into:
You also can use spread operator to do this
Maybe something like this:
Is this good enough? Or can't
c
actually get copied?For those who can't use ES6, you can use
lodash
orunderscore
.Or
ramda
.You can write a simple helper function for it. Lodash has a similar function with the same name: omit
Also, note that it is faster than Object.assign and delete then: http://jsperf.com/omit-key