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!

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *