YogeshChauhan.com
Object destructuring in JavaScript: Unpacking fields from objects passed as function parameter
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!

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

Understand Inheritance in PHP in this Basic Example (For Beginners)PHPHow to check if a link has http or https in it in JavaScript?JavaScriptLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQLThe SELECT DISTINCT Statement in SQLSQL/MySQLSocial Media Colors: LESS VariablesMiscWhat is PostgreSQL? How similar or different it is from SQL?Postgres