Object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables. What’s better, object destructuring can extract multiple properties in one statement, can access properties from nested objects, and can set a default value if the property doesn’t exist.
Normally, we access objects with the key. Nothing new :)
object.key
Let’s have quick look at the example below:
// object (Literal)
var user = {
name: "Hidayt",
city: "Delhi",
type: "Admin"
}
console.log(user.name); // Hidayt
We have a user object which contains user info (name, city, type). We will be using this example for object destructuring.
Object destructuring
Let’s use object destructuring and Destructuring the object into our variables.
// object destructuring
var {name, city, type} = user;
// access as a normal variable
console.log(name); // Hidayt
console.log(city); // Delhi
console.log(type); // Admin
You can access name directly instead of user.name
Now it can be accessible as a normal variable.
Destructuring makes code tidy and easy to access.
Top comments (8)
Here's my article on Object Destructuring in depth : dev.to/yuvgeek/use-object-destruct...
Thank you for sharing :)
Thanks.
I'am glad you liked it :)
Nice post
Thank you :)
Here is my detailed article on ES6 destructuring. Might throw more light on the topic.
Thank you for sharing. Hope people will jump for the depth knowledge