Object destructuring in ES6

I’ve started to talk about destructuring in ES6 in my previous article Array destructuring in ES6. The topic of this article is Object destructuring in ES6.

For example:

// ES5
var
object = {"name": "Jesus", "age": 33};
var name = object.name;
var
age = object.age;
// ES6
let object = {"name": "Jesus", "age": 33};
let name, age;
({name, age} = object);
Note: names of variables must match with names of object methods.
Otherwise:
let object = {"name": "Jesus", "age": 33};
let x, y;
({name: x, age: y} = object);

But if you love minimalism and Jesus:

let {name: x, age: y} = {"name": "Jesus", "age": 33};
Note: In the examples above variables are declared right in front of an assignment: let {…} = {…}. Of course, you can do it without “let”, use existing variables.
However, there is a small “trick”. In JavaScript if the main flow code (in other expressions) {…} is found, then this is taken as block.
{
// local variable only for this block
let a = 5;
alert(a); // 5
}
alert(a); //
Uncaught ReferenceError: a is not defined

Consequently:

let a, b;
{a, b} = {a:5, b:6}; //
Uncaught SyntaxError: Unexpected token =
// Solution:
({a, b} = {a:5, b:6}); // a = 5, b = 6

Default parameters if object methods are undefined:

let {a, b, c = 3} = {a: "1", "b": 2};
console.log(c); // 3

Computed object property names and destructuring:

let {["first"+"Name"]: x} = {firstName: "John"};
console.log(x); // John
let name = "a";
let {[name]: other} = {a: "string"};
console.log(other); // "string"

Nested object destructuring:

let {name, otherInfo: {age}} = {name: "John", otherInfo: {age: 12}};
console.log(name, age); // John 12

For of iteration and destructuring:

let people = [
{
name: 'Mike Smith',
family: {
mother: 'Jane Smith',
father: 'Harry Smith',
sister: 'Samantha Smith'
},
age: 35
},
{
name: 'Tom Jones',
family: {
mother: 'Norah Jones',
father: 'Richard Jones',
brother: 'Howard Jones'
},
age: 25
}
];
for (let {name: n, family: {father: f}} of people) {
console.log('Name: ' + n + ', Father: ' + f);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

Pulling fields from objects passed as function parameter

function userId({id}) {
return id;
}
function whois({displayName: displayName, fullName: {firstName: name}}) {
console.log(displayName + ' is ' + name);
}
var user = { 
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
}
};
console.log('userId: ' + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"

Links: