Here is the way you get value from an object:
var obj = { color: "blue"}console.log(obj.color); //blue
Destructuring Assignment:
Object
Destructuring Assignment is somehow different:
var {color} = { color: "green"}console.log(color); //green
It tells to looking for color property, so I get "green".
If I have muli pros (color, name, position, state): And I want to get color, and position properties.
var {color, position} = { color: "green", name: "Great", position: "Finland", state: "Who knows"}console.log(color); //greenconsole.log(position); //Finland
Function
If I have a fn which return an object: And from the object, I just want name and state.
function getObj(){ return{ color: "green", name: "Great", position: "Finland", state: "Who knows" };}var {name, state} = getObj();console.log(name); //Greatconsole.log(state); //Who knows
From the example, if you want to name something else:
{name: who, state: where}
function getObj(){ return{ color: "green", name: "Great", position: "Finland", state: "Who knows" };}var {name: who, state: where} = getObj();console.log(who); //Greatconsole.log(where); //Who knows
Array
If I have an array, from which I just want the first and the third element from the array:
var [first,,third] = ['first', 'second', 'third', 'forth'];console.log(first); //firstconsole.log(third); //third
If I want to forEach of array: and get the firstName
var people = [ { firstName: "Allen", secondName: "Hook", email: "allen@abc.com" }, { firstName: "Anton", secondName: "Tee", email: "tee@abc.com" }, { firstName: "Yui", secondName: "Gegg", email: "gegg@abc.com" }];people.forEach(({firstName}) => console.log(firstName));/* Allen Anton Yui * */
To make it clear:
people.foreach(function(person){ console.log(person.firstName);});//Destructuring people.foreach(function( {firstName} ){ console.log(firstName);});//Destructuring + Allowpeople.foreach( ( {firstName} ) => console.log(firstName); )
or:
var [, secondPerson] = people;function logEmail({email}){ console.log(email);}logEmail(secondPerson); //tee@abc.com