Destructuring Object and Array in Javascript

Destructuring Object and Array in Javascript

Destructuring is the way to unpack values from an array or properties from an object. Using Destructuring, we can take those values out of an array(or an object) and save them directly to other variables with just a single line of code, instead of taking one by one item or properties to variables.

//Using conventional way for extracting array values
const values = [1, 2, 3, 4];
let a = values[0];
let b = values[1];
let c = values[2];
let d = values[3];
//Using Array Destructuring for extracting values
const values = [1, 2, 3, 4];
let [a,b,c,d] = values;

Destructuring Array

In previous example we've seen the basic usage of array destructuring. Beyond that, we also have features like skipping array item and using rest operator.

Below is the example how to skip some array item and take only some selected values to other variables

const values = [1, 2, 3, 4];
//this will take value 1 to firstValue, skipped value 2, skipped value 3, and save value 4 to lastValue
//so firstValue is 1 and lastValue is 4
let [firstValue,,,lastValue] = values;

We can also use rest/spread operator to take values from any point of the array until the last value to a new array. Here is the example:

const values = [1, 2, 3, 4];
//this will save value 1 to a, 2 to b, and [3,4] to remainValues
let [a,b,...remainValues] = values;

In above code, ... is the rest operator. It will make rest values of variable values after 1 and 2 to be hold in variable remainValues.

We can use array destructuring either directly to an array variable or to an array returned by a function as well. See codes below:

function add(a,b){
  return[a, b, a+b];
}
//firstOp will hold first element(a) of the array returned by the add function
//secondOp will hold second element(b) of the returned array
//result will hold the third element(a+b) of the returned array
const [firstOp, secondOp, result] = add(2,3);

Destructuring Object

Not only available for array variables, destructuring is also available for object as well. Instead of extracting and object's properties one by one to some variables like this:

const name = {firstName: "John", middleName:"F.", lastName:"Kennedy"}
let firstName = name.firstName;
let middleName = name.middleName;
let lastName = name.lastName;

You can shorten your code above with help of object destructuring. Here is the way:

const name = {firstName: "John", middleName:"F.", lastName:"Kennedy"}
let {firstName, middleName, lastName} = name;

Take Object Properties and Save Them With Different Variable Name

When we take out the object properties to some variables, we don't always want to have variables with the same name as the properties. Sometime we want different names. We can do for sure.

const serverResponse = {success:true, data:{username:"Pegasus", photo:"somewhere.jpg"}}
const {data: user} = serverResponse;
console.log("User:",user);

the line const {data: user} = serverResponse; you take the data property from serverResponse and save it to a variable named user. The renaming code is the code {data: user}. data is a property of the object and user is the variable that will hold the property's value.

Destructuring Object in Function's Parameter

Object destructuring can also be used directly in parameter definition of a function.

function getFullName({firstName, middleName, lastName}){
  return firstName + " "+ middleName + " " + lastName;
}
const name = {firstName: "John", middleName:"F.", lastName:"Kennedy"}
const fullName = getFullName(name);

Look at the function's parameter definition ({firstName, middleName, lastName}). The curly brackets indicates that the function will take an object as its parameter and it will extract the object's properties: firstName, middleName, lastName into variables with those properties' name which will available inside the function scope.

Use rest operator in object destructuring

We can also use rest operator ... for object destructuring. Imagine a use case where you want to create an object variable that contain some properties of another object and also has some more properties as well. In that situation using spread operator might fit your need.

const personName = {firstName: "John", middleName:"F.", lastName:"Kennedy"};
const personInfo = {age: 55, height: 190};
const personCompleteInfo = {...personName, ...personInfo, countChildren: 3, isPresident: false};

In sample code above, we have a person data splitted in two variables: personName and personInfo. We don't want that so we think of joining all properties of those two object to one object. We also want to add other properties: countChildren and isPresident to that new object.

What would we do? We come to the rest operator as our helper.

With syntax const personCompleteInfo = {...personName, ...personInfo, countChildren: 3, isPresident: false}, we now have object personCompleteInfo with properties: firstName,middleName,lastName,age,height,countChildren, and isPresident. It will look like this:

new object.jpg

Conclusion

To summarize this about array and object destructuring:

  1. Using destructuring can shorten our code
  2. Destructuring is available for array or object variables
  3. When destructuring, we can utilize spread operator ... to make our code even more eficient.