As I have just finished my first phase of study with Flatiron School, it occurred to me that I should display a portion of what I learned for others to benefit from.
For this, I have chosen object destructuring.
Summary: Here we'll explore some JavaScript object destructuring methods that assign properties of an object to individual variables.
Let's say we have an object containing someone's elemental makeup reading, taken by an oriental philosopher. Follow this link to learn more.
let johnsElementalMakeup = {
wood: "13%",
fire: "17%",
earth: "23%",
metal: "22%",
water: "25%"
};
The traditional way (before ES6) to assign properties of the johnsElementalMakeup object to variables was the following:
let wood = elementalMakeup.wood;
let earth = elementalMakeup.earth;
Since ES6, we can now use the following:
let { wood: wo, fire: f, earth: e, metal: m, water: wa } = johnsElementalMakeup
Here, the variables of wo, f , e, m , and wa would be assigned to the values of wood, fire, earth, metal and water, respectively.
The basic syntax for this is:
let { key1: variable1, key2: variable2 } = object;
The identifier before the colon (:) is the key/property of the object and the identifier after the colon is the variable.
If the variables should have the same names as the keys of the object, we can simplify as shown:
let { wood, fire, earth, metal, water } = johnsElementalMakeup
console.log(wood, fire, earth) // "13%", "17%", "23%"
Each of the key names within johnsElementalMakeup are now variable names which are assigned to the respective percentage values.
Adding in a key name that doesn't exist within the object would result in that variable being assigned "undefined".
For more, including how to destructure nested arrays, I suggest you check out the documentation at MDN: Here.
Top comments (0)