ES6: 12 Use Destructuring Assignment to Assign Variables from Objects
We saw earlier how spread operator can effectively spread, or unpack, the contents of the array.
We can do something similar with objects as well.
Destructuring assignment is special syntax for neatly assigning values taken directly from an object to variables.
Consider the following ES5 code:
var voxel = {x: 3.6, y: 7.4, z: 6.54 };
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54
Here's the same assignment statement with ES6 destructuring syntax:
var x = voxel.x; // x = 3.6
var y = voxel.y; // y = 7.4
var z = voxel.z; // z = 6.54
const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54
If instead you want to store the values of voxel.x into a, voxel.y into b, and voxel.z into c, you have that freedom as well.
const { x : a, y : b, z : c } = voxel // a = 3.6, b = 7.4, c = 6.54
You may read it as "get the field x and copy the value into a," and so on.
Use destructuring to obtain the length of the input string str, and assign the length to len in line.
function getLength(str) {
"use strict";
const {length:len }= str; // means str.length =len
return len; // this will return str.length /12
}
console.log(getLength('FreeCodeCamp'));
"use strict";
const {length:len }= str; // means str.length =len
return len; // this will return str.length /12
}
console.log(getLength('FreeCodeCamp'));
ES6:13 Use Destructuring Assignment to Assign Variables from Nested Objects
const a = {
start: { x: 5, y: 6},
end: { x: 6, y: -9 }
};
const { start : { x: startX, y: startY }} = a;
console.log(startX, startY); // 5, 6
In the example above, the variable start is assigned the value of a.start, which is also an object.
let us use Use destructuring assignment to obtain max of forecast.tomorrow and assign it to maxOfTomorrow.
start: { x: 5, y: 6},
end: { x: 6, y: -9 }
};
const { start : { x: startX, y: startY }} = a;
console.log(startX, startY); // 5, 6
const LOCAL_FORECAST = {
today: { min: 72, max: 83 },
tomorrow: { min: 73.3, max: 84.6 } };
function getMaxOfTmrw(forecast) {
"use strict";
// change code below this line
const {tomorrow:{max:maxOfTomorrow }}=forecast;//
// change code above this line
return maxOfTomorrow;
}
console.log(getMaxOfTmrw(LOCAL_FORECAST)); // should be 84.6
today: { min: 72, max: 83 },
tomorrow: { min: 73.3, max: 84.6 } };
function getMaxOfTmrw(forecast) {
"use strict";
// change code below this line
const {tomorrow:{max:maxOfTomorrow }}=forecast;//
// change code above this line
return maxOfTomorrow;
}
console.log(getMaxOfTmrw(LOCAL_FORECAST)); // should be 84.6
Comments
Post a Comment