DEV Community

Cover image for JavaScript object destructuring usages you must know
Tapas Adhikary
Tapas Adhikary

Posted on • Originally published at blog.greenroots.info

JavaScript object destructuring usages you must know

Introduction

We use JavaScript objects to store data and retrieve it later. We store data(aka information) in key-value pairs. The key-value pair is also known as the object properties.

Here is an employee object with three properties: id, name, dept as keys and 007, 'James', and 'Spy' as values.

const employee = {
  id: 007,
  name: 'James',
  dept: 'Spy'
}
Enter fullscreen mode Exit fullscreen mode

Since ES6(ECMAScript 2015), JavaScript provides a mechanism to handle the properties of objects in a much more innovative way. The mechanism is called Destructuring(also known as destructuring assignment). It is more of a new syntax added to the language than a feature.

If you like to learn from video content as well, this article is also available as a YouTube video tutorial here: 🙂

Don't forget to SUBSCRIBE for future content.

In this article, we will learn about the most crucial usages of object destructuring you must know as a web developer. It will make you a competent and efficient developer. If you know any other cool usages, don't forget to let us know in the comment section below.

⭐ Use destructuring to retrieve values from an object

The most basic usage of object destructuring is to retrieve the value of a property key from the object.

const employee = {
  id: 007,
  name: 'James',
  dept: 'Spy'
}
Enter fullscreen mode Exit fullscreen mode

Traditionally, we will use the dot(.) notation or the subscript([]) notation to retrieve values from the object. The code snippet below shows the example of retrieving the value of id and name from the employee object using the dot notation.

const id = employee.id;
const name = employee.name;
Enter fullscreen mode Exit fullscreen mode

No doubt it works perfectly. But think about the tiring typing(or copy-paste-edit) work when you have to do it for many property values? That's where the destructuring assignment syntax comes as a savior.

To destructure a value from an object, you use a syntax like this,

const { id, name } = employee;
Enter fullscreen mode Exit fullscreen mode

Here, we use the object's key names to create variables and assign them with the value from the object for the same key. In the above code snippet, we retrieve the value of id and name without typing them in multiple lines.

Even if you have 20 more values to retrieve, it is just a matter of specifying those key names with commas. Such a relief!!!

⭐ Use destructuring to retrieve values from a nested object

In all practicality, your data object may not be as simple as the employee object we have seen so far. The object's key can have another object as a value and form a nested object. Let us now see how to retrieve the value for a key from a nested object.

Here is our employee object where the value of the dept key is an object. It has a property with the key address whose value is another object. Great, we are dealing with a nested object here.

const employee = {
  id: 007,
  name: 'James',
  dept: {
    id: 'D001',
    name: 'Spy',
    address: {
      street: '30 Wellington Square',
      city: 'Chelsea'  
    }
  }  
}
Enter fullscreen mode Exit fullscreen mode

Let's retrieve the value of the address property traditionally.

const address = employee.dept.address;
Enter fullscreen mode Exit fullscreen mode

It works, and the output is,

{
    "street": "30 Wellington Square",
    "city": "Chelsea"
}
Enter fullscreen mode Exit fullscreen mode

Now let us go one more level down and retrieve the value of the street property.

const street = employee.dept.address.street;
Enter fullscreen mode Exit fullscreen mode

Of course, we typed more, and the output is,

30 Wellington Square
Enter fullscreen mode Exit fullscreen mode

Now with destructuring, things are simple. You can define the key name using its predecessor key. So to retrieve the value of address, we will start with its predecessor key dept. So, dept is the top-level key with no predecessor. Hence the syntax is,

const { dept: { address } } = employee;
console.log(address);
Enter fullscreen mode Exit fullscreen mode

and for the street property,

const { dept: { address: { street } } } = employee;
console.log(street);
Enter fullscreen mode Exit fullscreen mode

Let's move to the next one.

⭐ Define a new variable with object destructuring

There could be a situation where you are unsure if the object has a specific key while retrieving its value. Also, you may want to create a new variable with a default value in case the key is unavailable in the object.

Let's take this employee object for an example,

const employee = {
  id: 007,
  name: 'James',
  dept: 'Spy'
}
Enter fullscreen mode Exit fullscreen mode

Now let's assume we are trying to retrieve the value of the age property, which is not present in the object. A traditional way to do that is,

const age = employee.age ? employee.age : 25;
Enter fullscreen mode Exit fullscreen mode

If we find the age property, access its value, and assign it to the variable else, assign a default value of 25. So, how will we do that with the object destructuring syntax we have learned so far?

It is pretty simple.

const { name, age=25 } = employee;
console.log(age);
Enter fullscreen mode Exit fullscreen mode

As you see, we can do it easily by specifying the key name along with the default value. It has a similar impact as the traditional way we have learned just now.

Hold on. The destructuring part has got more magic to show! How about creating a brand new variable and assigning a value computed using the object property values? Sounds complex? Here is an example,

const {name, dept, message = `${name} is ${dept}`} = employee;
console.log(message);  
Enter fullscreen mode Exit fullscreen mode

We create a message variable and assign a value computed using name and dept property values of the employee object. Powerful, eh?

The output is,

James is Spy
Enter fullscreen mode Exit fullscreen mode

⭐ How to use JavaScript object destructuring aliases?

In JavaScript object destructuring, you can give your destructured variables an alias name. It comes in very handy to reduce the chances of variable name conflicts.

const employee = {
  id: 007,
  name: 'James',
  dept: 'Spy'
}
Enter fullscreen mode Exit fullscreen mode

Let's assume your source code has an existing variable named dept. So if we use the same variable name in destructuring, there will be a name conflict.

Instead, you can use an alias name to create the variable with this new name. For example, we can use the alias name department in this case.

const { dept: department } = employee;
console.log(department); //Spy
Enter fullscreen mode Exit fullscreen mode

Please note, we have destructured with the alias name, not with the actual key name that is still not defined.

console.log(dept);
Enter fullscreen mode Exit fullscreen mode

Output,

error

I have shared this usage as a knowledge byte on Twitter a while back,


FOLLOW me on Twitter for more tips and content.

⭐ Handle dynamic name property with object destructuring

We often handle API response data as JavaScript objects. These objects may contain dynamic data such that, as a client, we may not even know the property key names in advance.

Let's understand it with an example(same employee object)

const employee = {
  id: 007,
  name: 'James',
  dept: 'Spy'
}
Enter fullscreen mode Exit fullscreen mode

Can we write a function that returns the value of the employee object properties when we pass a key as an argument? Yeah, so it means we will not hard-code the key name inside the function. It is dynamic for the function.

Here is the code snippet to showcase how we may call the function.

const id = getPropertyValue('id');
const name = getPropertyValue('name');

console.log(id, name); // 7 'James'
Enter fullscreen mode Exit fullscreen mode

Let's define it now.

function getPropertyValue(key) {
    const { [key]: returnValue } = employee;   
    return returnValue;
}
Enter fullscreen mode Exit fullscreen mode

Please note the square brackets([..]) around the key in the destructuring assignment. The key we pass to the function gets evaluated, and the value is retrieved from the object. Isn't that cool. It is efficient usage.

⭐ Destructure objects in the function argument and return value

You must learn this usage if you want to explore any modern JavaScript-based frameworks/libraries like React, Vue, Svelte, Angular, etc. You can use object destructuring to pass the property values as arguments to the function.

The employee object,

const employee = {
  id: 007,
  name: 'James',
  dept: 'Spy'
}
Enter fullscreen mode Exit fullscreen mode

Now let us create a simple function that creates a message using the name and dept property values to log into the browser console.

function logEmployee({name, dept}) {
  console.log(`${name} is ${dept}`); 
}
Enter fullscreen mode Exit fullscreen mode

Just realize how simple it is. You don't need to take the entire object as an argument and pick the required property values. You pass the values directly as function arguments and use them inside.

You can now call the function as,

logEmployee(employee); // James is Spy
Enter fullscreen mode Exit fullscreen mode

There is one more usage of object destructuring with function. If a function returns an object, you can destructure the values directly into variables. Let's create a function that returns an object.

function getUser() {
  return {
    'name': 'Alex',
    'age': 45
  }
}
Enter fullscreen mode Exit fullscreen mode

Now if you are interested to retrieve the value of the age property, you can do it like,

const { age } = getUser();
console.log(age); // 45
Enter fullscreen mode Exit fullscreen mode

It indeed saves lots of extra typing and time.

⭐ Use object destructuring in loops

The last(but not the least) usage we will be discussing is destructuring in loops. Let's think of an array of employee objects. We want to iterate through the array and want to use the property values of each of the employee object.

const employees= [
  { 
      'name': 'Alex',
      'address': '15th Park Avenue',
      'age': 43
  },
  { 
      'name': 'John',
      'address': 'USA',
      'age': 33
  },
  { 
      'name': 'Ravi',
      'address': 'Bangalore',
      'age': 16
  }
];
Enter fullscreen mode Exit fullscreen mode

You can use the for-of loop to loop through the employees object and then use the object destructuring assignment syntax to retrieve the details. Let us log the name and age of each employee in the browser console.

for(let {name, age} of employees) {
  console.log(`${name} is ${age} years old!!!`);
}
Enter fullscreen mode Exit fullscreen mode

Output,

image.png

That's so neat. We all love object destructuring by now.

Conclusions

Time is precious. The more you save on that, the more you can produce more. The object destructuring syntax is here to save you that time. Please use it in practice, if not already.

I'm thrilled to share my experiences on object destructuring with you using this article. Please let me know if you found it helpful. You can find all the source code used in this article from here,




Let's connect. I share my learnings on JavaScript, Web Development, Career, and Content on these platforms as well,

Top comments (24)

Collapse
 
dagropp profile image
Daniel Gropp • Edited

Nice 😎 this is an amazing and very useful feature. Another useful thing with object destructing is to destruct some properties and then use the spread operator to get the rest.

const obj = {name: Moses, age: 120, country: Egypt};
const {name, rest} = obj;
console.log(name); // “Moses”
console.log(rest); // {age: 120, country: “Egypt”}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
maxiqboy profile image
Thinh Nguyen • Edited

Since it is ..., it's not sread operator.

In Object Destructuring, these three dots is rest propertises,

Rest in Object Destructuring
The Rest/Spread Properties for ECMAScript proposal (stage 4) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a; // 10
b; // 20
rest; // { c: 30, d: 40 }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
atapas profile image
Tapas Adhikary

Awesome Daniel, Thanks for adding to the list. Have a great day.

Collapse
 
jonrandy profile image
Jon Randy 🎖️
const str = 'Kumquat'
const {length, [length-1]:last} = str

console.log(length) // 7
console.log(last) // 't'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kazuyastefan profile image
Stefan Grbic

I was playing a bit with at(), but it's not supported in all browsers.

const str = 'Kumquat'
const {length, last = str.split('').at(-1) } = str;

console.log(length) // 7
console.log(last) // 't' 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
atapas profile image
Tapas Adhikary

Mindblowing. Thanks, John for sharing.

Collapse
 
prajapatiparth profile image
Parth Prajapati

Here's one more for you.

// using destructuring to optionally add properties to object;

const isEmployee = true;

const person = {
  name: 'xyz',
  age: 28,
  ...isEmployee ? {     // if isEmployee is true, it will destructure the employee object
    employeeId: 'G548',
    department: 'procurement'
  } : {},   // else it will destructure this empty object
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
atapas profile image
Tapas Adhikary

Super. Thanks!

Collapse
 
mrdulin profile image
official_dulin • Edited

A lot of times, you don't need destructuring. Reasons:

  1. Avoiding variable conflicts
  2. Keep context and enhance readability
Collapse
 
atapas profile image
Tapas Adhikary

You can use aliases for the # 1 point.

2, agree but when you see the entire dev ecosystem(like with React I see) using it, I think, it is better to contribute that way.

Hey, thanks a lot for giving it a read and posting your views.

Collapse
 
froxx93 profile image
Froxx93

I would advise against variable definitions during destructing like this:

const {name, dept, message = `${name} is ${dept}`} = employee;
Enter fullscreen mode Exit fullscreen mode

What you're actually doing here is simply defining a default value for employee's property message. So as a side effect if your object actually has a property with that name, it will simply override your default value.

const employee = {
  name: 'John',
  dept: 'Service',
  message: 'This is me!'
}
const {name, dept, message = `${name} is ${dept}`} = employee;
console.log(message); // logs 'This is me!'
Enter fullscreen mode Exit fullscreen mode

It works, and you could still use it, but be aware of what's actually happening and consider writing 1 line of extra code to prevent possible unexpected behaviour.

Apart from that – A good overview to destructing. Gj!

Collapse
 
olsard profile image
olsard

Great! Thanks for sharing.

Collapse
 
atapas profile image
Tapas Adhikary

Welcmome 😀

Collapse
 
jackmcbride98 profile image
Jack McBride

Hi just testing the comment indentation levels on dev.to

Thread Thread
 
atapas profile image
Tapas Adhikary

Test passed? 😅

Thread Thread
 
jackmcbride98 profile image
Jack McBride

I'm building a blog site and im in the process of adding nested replies to comments, I wanted to see how the ui here handled nested comments. I wonder how far down you can go and will it keep indenting

Thread Thread
 
jackmcbride98 profile image
Jack McBride

12

Collapse
 
phyberapex profile image
PhyberApex

Awesome article! I use destruction all the time. Two things I find confusing tho is that nesting and alias share the colon operator (if you look closely they differ in syntax but I find it confusing). Same with default value and assignment to new attribute. So if you want to create a new attribute you need to make sure that one does never already exist on the object or you might get unwanted results.

~Cheers

Collapse
 
atapas profile image
Tapas Adhikary

Thank you! I completly agree.

Collapse
 
8bitsouvik profile image
Souvik Mandal

Thanks for elaborating destructuring in loops and and default value.😃
It'll help me to improve my current project

Collapse
 
atapas profile image
Tapas Adhikary

That's great. Very glad to know, you found it helpful

Collapse
 
gauravchandra profile image
Gaurav Chandra

Agree. The code needs to be human readable rather than concise. In any case the code gets compiled to a shorter form during build.

Collapse
 
lincoln_zhu profile image
Lincoln Zhu

Awesome post

Collapse
 
atapas profile image
Tapas Adhikary

Thank you very much!