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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
AND, OR and NOT boolean operators in Envision BasicEnvision BasicThe * arithmetic operator in Envision BasicEnvision BasicThe 8 Golden Rules of Programming I Have Learned in My CareerMiscellaneousCreate a responsive pricing table using simple HTML and CSSCSSNATURAL JOIN in PostgresPostgresHow to define visibility for a property in PHP?PHP