Destructuring of Objects
Destructuring is a concise way of extracting values from objects:
var expense = { type: 'Travel', amount: 30 } //var type = expense.type; //var amount = expense.amount; const {type, amount} = expense; console.log(type); console.log(amount);
Destruturing can be useful in function arguments as well because it enables using a function to handle multiple object types that have common properties:
var expense = { type: 'Travel', amount: 30 } const exchange = 10; const convert = ({amount})=>{ return amount * exchange; } console.log(convert(expense)); // 300
Destructuring of Arrays
In the case of arrays, destructuring assigns array elements to variables. In this case destructuring uses brackets instead of curly braces and the order of variable names matched the order of elements in the array:
const colors = ['red', 'green', 'blue', 'yellow']; const [color1, color2] = colors console.log(color1); //red console.log(color2); //green
When destructuring arrays we can also use the rest operator as follows:
const colors = ['red', 'green', 'blue', 'yellow']; const [color1, color2, ...rest] = colors console.log(color1); //red console.log(color2); //green console.log(rest); //["blue","yellow"]
Destructuring an Array of Objects
Destructuring can also be done with an array of objects. In the following example the Google object is assigned to first and the Menlo Park is assigned to the location variable. Line 7 combines destructuring of an array and destructuring of an object.
const companies = [ {name: 'Google', location: 'Mountain View'}, {name: 'Facebook', location: 'Menlo Park'}, {name: 'Uber', location: 'San Francisco'}, ]; const [first, {location}] = companies; console.log(first); // Object for google console.log(location); // Menlo Park
Destructuring an Array inside an Object
The following example involves destructuring an array inside an object:
const google = { locations: ['Mountain View', 'New York', 'London'] }; const {locations: [location]} = google; console.log(location); // Mountain View
Converting Arrays to Objects
The following code uses an array of arrays to generate an array of objects using destructuring:
const classes = [ [ 'Chemistry', '9AM', 'Mr. Darnick' ], [ 'Physics', '10:15AM', 'Mrs. Lithun'], [ 'Math', '11:30AM', 'Mrs. Vitalis' ] ]; const classesAsObject = classes.map(item=>{ var [subject, time, teacher] = item; return {subject, time, teacher}; }); const classesAsObject2 = classes.map(([subject, time, teacher])=>{ return {subject, time, teacher}; }); console.log(classesAsObject); console.log(classesAsObject2);