Destructuring is a convenient syntax feature in JavaScript that allows you to extract values from objects or arrays and assign them to variables in a more concise and readable way. Here’s how to destructure an object in JavaScript:
Example
const Student = {
firstName: 'Krunal',
lastName: 'Lathiya',
university: 'GTU',
enrollno: 110470116021
};
const { firstName, lastName, university, enrollno } = Student;
console.log(firstName);
console.log(lastName);
console.log(university);
console.log(enrollno);
Output
First, we defined the object, and then we destructure that object into four different variables. Then, we logged that four different variables.
It is called a “destructuring assignment” because it “destructurizes” by copying items into variables.
It does not destroy the object. So we can still log that object. It does not modify. It stays the same.
Output
Assignment without declaration
The variable can be assigned its value with destructuring separate from its declaration.
let a, b;
({a, b} = {a: 1, b: 2});
console.log(a); // 1
console.log(b); // 2
Nested destructuring of an object
When you have an object with nested properties, you can extract the values from the nested objects and assign them to variables using destructuring syntax.
Example
const person = {
name: 'Krunal L',
age: 30,
address: {
city: 'Rajkot',
country: 'India'
}
};
const { name, address: { city, country } } = person;
console.log(name);
console.log(city);
console.log(country);
Output
Krunal L
Rajkot
India
In this example, the name property is extracted from the person object, while the city and country properties are extracted from the nested address object.
The destructuring syntax allows you to access nested properties directly by specifying the nested structure within the curly braces {}.
You can also assign new variable names when destructuring nested properties.
const person = {
name: 'Krunal L',
age: 30,
address: {
city: 'Rajkot',
country: 'India'
}
};
const { name: fullName,
address: { city: cityName, country: countryName } } = person;
console.log(fullName);
console.log(cityName);
console.log(countryName);
Output
Krunal L
Rajkot
India
In this example, the name, city, and country properties are assigned to the fullName, cityName, and countryName variables, respectively.
That’s it.