Destructuring Overview
ES5:
var expense = {
type: 'Business',
amount: '$45 Usd'
}
var type = expense.type;
var amount = expense.amount;
ES6:
const {type} = expense; //Equivalent to expense.type and will be assigned to a property of the same name
const {amount} = expense;
//Could be simplified more:
const {type, amount} = expense;
type; -> 'Business'
amount; -> '$45 Usd'
Destructuring Arguments Object
//ES5
var savedFiled = {
extension: '.jpg',
name: 'report',
size: 104040
}
function fileSummary(file){
return file.name + file.extension + file.size //Duplicating the file.name
}
//ES6
function fileSummary({name, extension, size}){
return name + extension + size /
}
Destructuring Array:
const companies = [
'Google',
'Facebook',
'User'
]
const [name, name2, name3 ] = companies; //Please not we need to use square braces
name1 -> Google
name2 -> Facebook
//Without destructing:
const name1 = companies [0]
//Could also use the rest operator
const [name, ...rest ] = companies;
console.log(rest) -> ["Facebook", "User"]
More example
const companies = [
{'Google', location: 'Mountain View},
{'Facebook', location: 'Africa View}
]
//ES5
var location - companies[0].location
//ES6
const [{location}] = companies
//Will output Mountain View
//More eg:
const Google {
locations: ['Mountain View', 'New York', 'London']
}
//I want you to look into the object, fund the locations property, then pull the first element
const {locations : [location]} = Google
Practical example:
//Need to convert [4,5] into {"x":4,"y":5} for an API call
const points = [
[4,5],
[10,1],
[0,40]
]
//Eg1
points.map(pair => {
const x = pair.[0];
const y = pair.[1];
});
//Eg2
points.map(pair => {
const [x,y] = pair;
});
//Eg3:
points.map(([x,y]) => {
return {x: x, y: y};
});
//Eg4
points.map(([x,y]) => {
return {x, y};
});