JavaScript ES6 Destructuring

This is the array of data we’re going to be working with. It is an array of 2 Objects:

const people = [
   { name: "Bob", age: 50 },
   { name: "Jan", age: 45 }
];

First, I’ll destructure the people array by pulling out the two contents and giving them separate names. Although the syntax looks a little weird, these two destructured objects should have unique names because they are variables.

const [person1, person2] = people;

So how would we destructure the two objects? It would be similar to destructuring the array except since we are working with a JS object, we will use curly braces.

const { name, age } = person1;

console.log(name);
// prints "Bob"

You can also define these properties to have unique names:

const { name: name1, age: age1 } = person1;

console.log(name1);
// prints "Bob"

There is also a way to define a value for an object’s variable if that object doesn’t currently have one. This is called giving the object a default value. As an example, let’s say that our person Bob was defined without an age:

const people = [
   { name: "Bob" },
   { name: "Jan", age: 45 }
];

We can add one for him when we are destructuring by doing this:

const { name: name1, age = 42 } = person1;

console.log(age);
// prints 42

But if Bob’s age was set to 50 when the array was defined and we used the above line const { name: name1, age = 42 } = person1, his age would not change.

console.log(age);

// prints 50

How would you handle an object within an object within an array?

const people = [
   { name: "Bob", age: 50, children: {
      son: "Bobby",
      daughter: "Jill"
   }
   },
   { name: "Jan", age: 45 }
];
const [bob, jan] = people;

const { name, age, children } = bob;

console.log(children.son);
// prints "Bobby"

OR

const { name, age, children: {son, daughter} } = bob;

console.log(son);
// prints "Bobby"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s