Destructuring in ES6
July 22, 2017 Leave a comment
Destructuring in ES6 is about pulling out certain properties from objects into other variables. It can also be used to extract values from arrays into variables.
Here’s an example object:
let customer = { name: 'Great Customer Inc', address: 'Los Angeles' }
Here’s how we can pull out the name and address properties from the customer with destructuring:
let {name, address} = customer
We can then use “name” and “address” like normal variables afterwards:
console.log(name) console.log(address)
The properties to be extracted from the customer are enclosed within curly braces followed by the equal sign and then the variable from which we want to pull those properties. The variable names within the curly braces must be the same as properties in the JSON object. The above is a short-hand for the following extended version:
let name = customer.name let address = customer.address
Destructuring in methods
We can use the same technique in method signatures. Here’s an example:
let printMe = function({name, address}) { console.log(`${name}, ${address}`) } printMe(customer)
Note how the name and address properties are pull out from the customer object we’ve passed in. The order of the properties in the JSON object doesn’t matter, the following is equally good:
printMe({address: 'Los Angeles', name: 'Great Customer Inc'})
…so it’s fine to have “address” first and “name” second even if the order is different in the method signature. The property names will be matched up.
Destructured input parameters can be mixed with “normal” ones:
let printMe = function({name, address}, greeting) { console.log(`${name}, ${address}: ${greeting}`) } printMe({address: 'Los Angeles', name: 'Great Customer Inc'}, 'Good morning')
We can even have multiple destructured parameters:
let printMe = function({name, address}, {prodName, qty}, greeting) { console.log(`${name}, ${address} is buying ${qty} ${prodName}s: ${greeting}`) } printMe({address: 'Los Angeles', name: 'Great Customer Inc'}, {prodName: 'chair', qty: 123}, 'Good morning')
In arrays
Array destructuring uses square brackets instead of curly braces. Here’s an example:
let languages = ['C#', 'Java', 'JavaScript', 'F#', 'Ruby'] let [firstChoice] = languages
firstChoice will get the value C#. Similarly in…
let [firstChoice, secondChoice] = languages
…secondChoice will be Java. The order in the array destructuring defines which variable will get which element from the array.
We can pull out all remaining languages into a separate array using the … spread operator:
let [firstChoice, secondChoice, ...others] = languages
“others” will be an array:
["JavaScript","F#","Ruby"]
We can transform an array of arrays into objects. Say that first and last names are arranged into arrays like here:
let names = [ ['Mary', 'Williams'], ['John', 'Cooper'], ['Jane', 'Collins'], ['George', 'Noble'] ]
We can quickly transform this array into an array of objects:
let fullNames = names.map(([firstName, lastName]) => { return {firstName, lastName} })
Here’s the array with full names:
[{"firstName":"Mary","lastName":"Williams"},{"firstName":"John","lastName":"Cooper"},{"firstName":"Jane","lastName":"Collins"},{"firstName":"George","lastName":"Noble"}]
Mixing array and object destructuring
We can mix the two styles to dig into an array of objects. Here’s the enhanced list of programming languages:
let languages = [{'name': 'C#', 'style': 'OOP', 'typed': true}, {'name': 'Java', 'style': 'OOP', 'typed': true}, {'name': 'JavaScript', 'style': 'script', 'typed': false}, {'name': 'F#', 'style': 'functional', 'typed': true}, {'name': 'Ruby', 'style': 'OOP', 'typed': false}]
Suppose that we want to read out the name of the first language object in the array. Here’s how to do that:
let [{name}] = languages
So we first dig into the array, get its first element and extract its “name” property.
Next we reverse the order and take an object which has an array:
let functionalLanguages = { 'purpose': 'computations', 'examples': ['Scala', 'F#', 'Haskell', 'Erlang'] }
We want to get the first element from the examples array. Here’s how to do it:
let {examples: [firstExample]} = functionalLanguages
Now we first dig into the object, take its examples array and extract the first element out of it. firstExample will get the value Scala.
View all posts related to JavaScript here.