Nested Object Destructuring in JavaScript

Image for post
Image for post

Why Use It?

const user = {
name: 'Joe',
age: 25,
bills: {
mortgage: 1000,
car: 250,
phone: 0
}
}
function showBillsPaid(user) {
console.log('Hello, '+ user.name)
console.log('Your mortgage payment was: $' + user.bills.mortgage)
console.log('Your car payment was: $' + user.bills.car)
console.log('Your phone payment was: $' + user.bills.phone)
}
showBillsPaid(user)// Hello, Joe
// Your mortgage payment was: $1000
// Your car payment was: $250
// Your phone payment was: $0

Nested Object Destructuring

const user = {
name: 'Joe',
age: 25,
bills: {
mortgage: 1000,
car: 250,
phone: 0
}
}
function showBillsPaid({name, bills: {mortgage, car, phone}}) {
console.log('Hello, '+ name)
console.log('Your mortgage payment was: $' + mortgage)
console.log('Your car payment was: $' + car)
console.log('Your phone payment was: $' + phone)
}
showBillsPaid(user)// Hello, Joe
// Your mortgage payment was: $1000
// Your car payment was: $250
// Your phone payment was: $0
// this doesn't work!const { bills: {} } = user

Default Values

const user = {
age: 25,
bills: {
mortgage: 1000,
car: 250,
phone: 0
}
}
function showBillsPaid({name = 'User', bills: {mortgage, car, phone}}) {
console.log('Hello, '+ name)
console.log('Your mortgage payment was: $' + mortgage)
console.log('Your car payment was: $' + car)
console.log('Your phone payment was: $' + phone)
}
showBillsPaid(user)// Hello, User
// Your mortgage payment was: $1000
// Your car payment was: $250
// Your phone payment was: $0
const user = {
name: 'Joe',
age: 25,
bills: {}
}
function showBillsPaid({name = 'User', bills: {mortgage = 1000, car = 250, phone = 0}}) {
console.log('Hello, '+ name)
console.log('Your mortgage payment was: $' + mortgage)
console.log('Your car payment was: $' + car)
console.log('Your phone payment was: $' + phone)
}
showBillsPaid(user)// Hello, Joe
// Your mortgage payment was: $1000
// Your car payment was: $250
// Your phone payment was: $0

Full-Stack Developer, Software Engineer, and UX/UI Aficionado

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store