How to Destructure Object in Javascript
In this tutorial, you will learn how to destructure object in javascript. Object destructuring is one of the most commonly used ES6 (ECMAScript 6) javascript features. With the help of object destructuring, you can extract properties from an object with a single line of code.
A property in the object is just a key-value pair. While destructuring an object, the variable name and key name should be the same. But if you are planning to use a different variable name, then you can provide an alias.
You can also assign a default value to the variable if a property does not even exist. I suggest you to have a look over MDN docs to get more detailed information about object destructuring since we are not going to cover much in this tutorial.
In the following example, we will destructure an object, form a template string and display that on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element and theh1
element have“Get”
and“Result”
asinnerText
respectively. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Get</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div { display: inline-block; } button { display: inline-block; padding: 10px 20px; }
Javascript
- We have selected the
button
andh1
elements using thedocument.querySelector()
method and stored them in thebtnGet
andresult
variables respectively. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we have a local
users
object. - We destructured the
user
object and as a result, we got 4 variablesa
,b
,c
, andd
. As you can see, there is no property by key named
, so we have created an aliasd1
ford
and also assigned a default value“Rita”
to it. - We are forming a template string using all variables and displaying that in the
h1
element using theinnerText
property.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); btnGet.addEventListener('click', () => { let users = { a: 'Marks', b: 'James', c: 'Peter', }; let {a, b, c, d:d1 = 'Rita'} = users; result.innerText = `a: ${a} - b: ${b} - c: ${c} - d: ${d1}`; });