ES6 Destructuring Objects
With es6 deconstructing objects gives us a nice way of extracting keys of objects into variables. Combined with the rest operator this comes in very useful when you need to unset an item or two in an object.
A basic example of deconstructing an object is.
const obj = {key_one: 'value one', key_two: 'value two'_};
const { key__one } = obj;
console.log(key_one); // value one
You can also change the name of the variable that you extract like.
const { key_one: new_name } = obj;
Now the value assigned to new_name
is the value of key_one
in the object
this is value one
.
As I mentioned previously, there is a rest operator defined like ...
. This can
be used to remove an item from an object and also give us what's left over.
const { key_one, ...theRest } = obj;
console.log(theRest); // {key_two: 'value two'}
Now the rest feature is new in js and at the time of writing this I was getting
an error like SyntaxError: Unexpected token
. To fix this I need to use a plug
in with the babel transpiler. I am a webpack user and added it to my babel
loader rule like so.
...
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
plugins: ['transform-object-rest-spread'],
presets: ['env']
}
},
]
}
]
...