JavaScript Object Destructuring
const developer = {
username: 'NotAbug',
email: 'notabug@pls.com',
networks: {
instagram: {
username: '@notABug-ig',
link: 'https://instagram.com/notabug'
},
twitter: {
username: '@notABug-tw',
link: 'https://twitter.com/notabug'
},
youtube: {}
}
}
Simple object destructuring.
const { username } = developer
console.log(username) // NotAbug
Nested destructuring and rename.
const {
networks: {
instagram: { username: instagramUsername },
twitter: { username: twitterUsername },
youtube: { username: youtubeUsername = null }
}
} = developer
console.log(instagramUsername) // @notABug-ig
console.log(twitterUsername) // @notABug-tw
console.log(youtubeUsername) // null
Destructuring and rest operator.
const { networks: { instagram, ...restNetworks } } = developer
const newInstagram = {
username: '@definitelyNotABug',
link: instagram.link
}
developer.networks = {
...restNetworks,
instagram: newInstagram
}
console.log(developer.networks.instagram.username) // @definitelyNotABug