Advance Object Destructuring Assignment In JavaScript

Muhammad Asad Attari
3 min readJul 26, 2022

--

We will Learn some smart and advance ways to destructure objects. Maybe you know some of methods i’m going to discuss but surely you will know some new one.

Method 1 — access only specific keys

destructuring object simply means you are separating object entries which you require.

  1. On right side you have to place object
  2. on left side define data type of object key, keys must be equivalent to object keys and you can directly access keys directly. see below
Output Method 1

Method 2 — destructuring with rest operator (…)

In case you want to access one specific key and create another object for remaining elements
Note: If you don’t know about spread operator please visit official MDN JS docs → JavaScript Spread Operator

destructuring with spread operator
Output Method 2

Method 3 — Destructuring with nested objects

we can destructure nested object like below i’have done.

destructure nested object
method 3 output

Note: In Above code if you want to access “b”, you will get an error, “b” is not defined, but why? 💭💭

Actually when you are destructuring object and assign value at the time of destructuring property assigned to the target object, you only get the target not the property. This is the rule of thumb no need to worry about it.

Assigning Default Value while Destructuring

you can initialize a property with default value if not exist in object,

default value for non-existing property
output default value destructuring

Conclusion

We have discussed three ways to destructure objects and assigning a default value, there are much more about objects which are not part of this article we will discuss about that in another article, if you have any question please let me know thanks.

--

--

Muhammad Asad Attari
Muhammad Asad Attari

Written by Muhammad Asad Attari

Software Engineer | Full Stack Developer | DevOps Engr.

No responses yet