Add example for destructuring nested objects (#24133)

Also changed styling to be more consistent
This commit is contained in:
Oğuzcan Yavuz
2018-12-07 04:27:24 +03:00
committed by Manish Giri
parent fbab448003
commit 172ec835d7

View File

@ -35,7 +35,7 @@ The examples above show the benefit of using the ES6 Destructuring Assignment.
You can also use Destructuring on objects using a similar syntax
```js
const fullName = { first: "John", last: "Smith"};
const fullName = {first: "John", last: "Smith"};
const {first, last} = fullName;
console.log(first, last); // John Smith
@ -44,7 +44,7 @@ console.log(first, last); // John Smith
Object Destructuring Assignment is a little bit different because the object must have properties with the names you are assigning. Therefore the code below would not work as intended.
```js
const fullName = { first: "John", last: "Smith"};
const fullName = {first: "John", last: "Smith"};
const {firstName, lastName} = fullName;
console.log(firstName, lastName); // undefined undefined
@ -58,11 +58,21 @@ const {propertyName: desiredVariableName} = obj
Our previous example would be rewritten as follows:
```js
const fullName = { first: "John", last: "Smith"};
const fullName = {first: "John", last: "Smith"};
const {first: firstName, last: lastName} = fullName;
console.log(firstName, lastName); // John Smith
```
You can also use Destructuring on nested objects.
```js
const person = {firstName: "John", lastName: "Smith", address: {city: "Istanbul", country: "Turkey"}};
const {address: {city, country}} = person;
console.log(city, country); // Istanbul Turkey
```
**Array Destructuring with rest**
When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern: