Destructuring allows conveniently extracting values from arrays and objects into distinct variables. This elegant unpacking syntax makes code more readable compared to traditional property access.
In this article we’ll focus specifically on the power of object destructuring to simplify JavaScript code working with nested data.
Motivating Object Destructuring
First consider extracting values from a typical API response:
const user = {
id: 101,
email: 'a@b.com',
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA'
}
};
// Verbose extracting without destructuring
const id = user.id;
const email = user.email;
const street = user.address.street;
const city = user.address.city;
We have to manually grab every desired property.
Now compare with destructuring:
const {id, email, address: {street, city}} = user;
// So clean!
In a single line we cleanly extract exactly the pieces we need from arbitrary nesting.