Destructuring objects in JavaScript
Destructure in simple terms means to destroy the structure of something and that is exactly what I want to talk about. Let me start with some analogy
Look at the image above with the lego blocks nicely placed into position, we can see some order in how its arranged. What if we are interested only in the blue blocks and we remove them?
Imagine the image above is an object with different properties and we are interested in the blue properties
According to MDN destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables
Now lets relate that to code, shall we? I will start with how I personally used it a while back
How I used destructuring in real code
I had a user object saved in the local storage in a javascript application we are building
currentUser = {
"id": 24,
"name": "John Doe",
"website": "http://mywebsite.com",
"description": "I am an actor",
"email": "example@example.com",
"gender": "M",
"phone_number": "+12345678",
"username": "johndoe",
"birth_date": "1991-02-23",
"followers": 46263,
"following": 345,
"like": 204,
"comments": 9
}
At one point I only needed the users id
and the username
in a new object. This means that I have to ignore majority of the properties
let { id, username } = this.currentUser; //where this.currentUser is the object above
This will create two variables id
and the username
and assign them values from the object
console.log(id) // 24
console.log(username) //johndoe
Syntax
- Basic syntax
Note that both sides of the assignment are objects and the property names have to be the same in the basic syntax as used for the user above and as shown below
var {p, q} = {p: 42, q: true, r: 'name'}
console.log(p) // 42
console.log(q) //guess what it will be
2. assigning to new variable names
You can use different names of the properties in the new object you are creating
var {p: foo, q: bar} = {p: 42, q: true, r: 'names'}
console.log(p) // Uncaught ReferenceError: p is not defined
console.log(foo) // 42
This is what I use mostly for now, if you want to dive deeper into this then checkout the MDN docs on this
SideNote: Destructing to me looks like pattern matching in Elixir