YogeshChauhan . com

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.

Let's create another function to get the username and firstname.


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

Let's create another function to get the lastname.


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!

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Order By and Group By in PostgresPostgresA list of wp-cli commands to use via SSHWordPressCheck if mixin is being called in a style rule or not in SCSSSCSSclip and clip-path properties in CSSCSS3 JavaScript methods to use when you want to go back and forth in historyJavaScriptHow to create a new HTML element programmatically using JavaScript?HTML