Yogesh Chauhan's Blog

Object destructuring in JavaScript: Unpacking fields from objects passed as function parameter

in JavaScript on June 21, 2020

We saw how Destructuring works in arrays and objects in this post: Array Destructuring And Object Destructuring In JavaScript

Let’s unpack a full JSON object and use as a parameter of a function in this post.

Let’s create an object first


const user = {
  userid: 1,
  username: 'YC',
  blog: 'yogeshchauhan.com',
  fullName: {
    firstName: 'Yogesh',
    lastName: 'Chauhan'
  }
};

Let’s create a simple function that returns userid from the object above.


function userId({userid}) {
  return userid;
}

console.log(userId(user)); // 1

Destructuring makes it really easier to pass the object and get only the required values in return.

Function to get the username and first name


function getUsername({username, fullName: {firstName: name}}) {
  return `${name}'s username is ${username}`;
}

console.log(getUsername(user));  // Yogesh's username is YC

So, in this example, we created a function named as getUsername that takes object as a parameter. Now, in the parameter section, we are using destructuring statement to get the required data like username and fullName from the object. AT the same time we are assigning the value of firstName to a variable name. 

Function to get the last name


function getLastname({fullName: {firstName: fname, lastName: lname}}) {
  return `${fname}'s last name is ${lname}`;
}

console.log(getLastname(user));  // Yogesh's last name is Chauhan

That’s it. 

Destructuring makes it a lot easier to unpack the object while we are in the parameter section. One more wonder from JS!


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
What’s the difference between visibility: hidden and display: none?CSSHow to use @supports rule in CSS?CSSOpen Source Security Tools for Defense SecurityMiscellaneousAccessing and Setting features of JavaScript ObjectsJavaScriptWhat is the correct way to enqueue multiple CSS files in WordPress?WordPressWhy do we need HAVING Clause in SQL?SQL/MySQL