Last active
November 14, 2018 04:43
-
-
Save emfluenceindia/955d93b8f196c00fe98521a1f805882f to your computer and use it in GitHub Desktop.
ES6 Object Destructuring - How it works: Simple example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Declare a JavaScript complex object | |
const user = { | |
name: 'Subrata Sarkar', | |
age: 47, | |
gender: 'Male', | |
location: { | |
address: { | |
aptno: 'D3', | |
bldg: 'City Heights - Phase 9', | |
street:'54 Express Avenue' | |
}, | |
country: 'India', | |
city: 'Kolkata', | |
zip: '999999' | |
}, | |
about: { | |
hobby:[ | |
'Coding', | |
'Traveling', | |
'Photography' | |
], | |
}, | |
role: 'Author' | |
} | |
// The whole object | |
console.log(user); | |
//Use Object Destructuring now... | |
// Step 1: Simple destructing | |
const {name, age } = user; | |
console.log(name, age); | |
// Step 2: Extract nested object | |
const {location: {address}} = user; | |
console.log(address); | |
// get single values from address object | |
console.log('Street: ' + address.street); | |
// Step 3: Extract array | |
// nested within another nested object | |
const {about} = user; | |
console.log(about.hobby); | |
// Step 4: looping the array | |
// Since hobby is an array, we can run map() | |
about.hobby.map(item=>{ | |
console.log(item); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment