The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects. In this case, we are going to see how destructuring works for objects.
const user = {
userName: 'fbarrios',
firstName: 'Freddy',
lastName: 'Barrios',
address: {
street: '52',
zipcode: '110007',
}
const { firstName } = user
console.log(firstName); // Freddy
This is the same as…
const firstName = user.firstName
It is possible to set default values, in case the property doesn’t exist or is undefined.
const { phone = '0000000' } = user
console.log(phone) // 0000000
A property can be renamed when it’s destructured.
const { username: displayName } = user
console.log(displayName); // Freddy
You can rename and set a default value for a property
const { phone: phoneNumber = '0000000' } = user
console.log(phoneNumber) // 0000000
When the object has another one nested it’s destructured in the following way
let { address: { street } } = user
console.log(street) // 52
Destructuring can be used with the arguments of a function
function fullname({firstName, lastName}) {
return `${firstName} ${lastName}`;
}
console.log(fullName(user)); // Freddy Barrios
Computed property names can be used with the destructuring assignment.
const key = 'username'
const { [key] } = user
Rest operator in object destructuring
This operator (...) collects all properties that weren’t picked off during object destructuring
const { address, …restProperties } = user
console.log(address);
/*
{
street: '52',
zipcode: '110007',
}
*/
console.log(restProperties); /
{
userName: 'fbarrios',
firstName: 'Freddy',
lastName: 'Barrios',
}
*/
As you can see, object destructuring is very useful and gives us another way to write better code.
Top comments (0)