Back
Featured image of post ES6 Destructuring Array and Object

ES6 Destructuring Array and Object

Destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Array Destructuring

const alphabet = ['A', 'B', 'C', 'D', 'E'];
const number = [1, 2, 3, 4, 5];

Let’s say we want to get the first and second element of the array. The very normal way is by doing this.

let first = alphabet[0]; //return 'A'
let second = alphabet[1]; //return 'B'

However, we’re trying to get more values from the array, the code will be long and difficult to read. Let’s see how we can handle this by better way.

let [first,second] = alphabet;
console.log(first); //return 'A'
console.log(second); //return 'B'

Skip certain value

If we want to avoid from getting some value or skip certain indexes from the array. It can be easily done by putting empty value there. For example, now we wanted to get the first index value ‘A’ and the fourth index value ‘D’

let [first, , ,fourth] = alphabet
console.log(first); //return 'A'
console.log(fourth); //return 'D'

Spread Operator …

If now we want to get the all value from array except the second index ‘B’. This is where Spread Operator come into play. index value ‘D’

let [first, ,...rest] = alphabet
console.log(first); //return 'A'
console.log(rest); //return ['C','D','E']

Combine Array

Normal way to combine 2 array is by using the method call “concat”

let combineArray = number.concat(alphabet);
console.log(combineArray); //return [1,2,3,4,5,'A','B','C','D','E']

And this is how it can be done by using spread operator

let combineArray = [...number,...alphabet];
console.log(combineArray); //return [1,2,3,4,5,'A','B','C','D','E']

Working spread operator with function

Let’s say we have one function which takes 2 parameters and return an array with diffrent math operation.
Normal way usually will be like this.

function mathOperation(x,y){
     return [x+y,x-y];
}

let mathArray = mathOperation(10,3);
let sum = mathArray[0];
let subtract = mathArray[1];

console.log(sum); //return 13
console.log(substract); //return 7

With array destructuring, we can shorten down the code

let [sum,subtract] = mathOperation(10,3);

console.log(sum); //return 13
console.log(substract); //return 7

we also can set the default value that will be used when there is no parameters to pass in

let [sum,subtract, multiply = "No multiplication"] = mathOperation(10,3);
console.log(multiply); //return 'No Multiplication'

//Edit function
function mathOperation(x,y){
     return [x+y,x-y,x*y];
}

console.log(multiply); //return 30

Object Destructuring

const CompanyOne = {
    name: 'Google',
    age: 22,
    headquarter: {
        city: 'Mountain View',
        state: "California"
    }
}

const CompanyTwo = {
    name: 'Amazon',
    age: 26,
    headquarter: {
        city: 'Seattle',
        state: "Washington"
    }
    founder: 'Jeff Bezos'
}

Destructuring the object is almost similar with the array destructring.
Let’s say now we want to get the properties name and age from the object.

let {name, age} = CompanyOne;
console.log(name); //return 'Google'
console.log(age); //return 22
Note: the variable inside the curly braces need to be exactly matched with the properties name.

Customize variable name from getting object value

By adding the colon : symbol we can then customize our variable name.

// let { name: companyName, age: companyAge } = CompanyOne;
console.log(companyName); //return 'Google'
console.log(companyAge); //return 22

we also can set the default value that will be used when there is no parameters to pass in

let { name: companyName = "Others", age: companyAge } = CompanyOne;
console.log(companyName) //return 'Others' when Company One object doesn't have the property of name

Spread Operator in object

For example we want the first property into one variable and the rest will be another variable.
It’s works quite similar like array destructuring with spread operator
The variable otherInfo is an object data type and holding the rest of the properties value except name

let { name: companyName, ...otherInfo } = CompanyOne;
console.log(companyName); //return 'Google'
console.log(otherInfo); 
/* { age: 22,
     headquarter: {
        city: 'Mountain View',
        state: "California"
    }}*/  

Desturcutre the object within an object

let { name: companyName, headquarter: { city, state } } = CompanyOne;
console.log(city) //return 'Mountain View'
console.log(state) // return 'California'

Concatenate and Overwrite object

By using spread operator with 2 object together, it will be first check if they have the same properties field. If Yes the value from second object will overwrite the first object. If No it will then create that field which the value respectively.

var otherCompany = { ...CompanyOne, ...CompanyTwo }
console.log(otherCompany)
/* { name: 'Amazon'
     age: 22,
     headquarter: {
        city: 'Mountain View',
        state: "California"
     founder:'Jeff Bezos'
    }}*/  

Object Destructuring in function

Object destructure in function is very useful when we have a large json data which holding many properties but there are only few value we are interested.
Regular way is to first pass in the entire object then only start access the property value by using dot notation

function checkCompany(company) {
    console.log(company.name); //return 'Google'
    console.log(company.age); //return 22
}

checkCompany(CompanyOne)

With object destructuring, we can straight away pass in the value we want according to their object name in the curly braces.

function checkCompany({ name, age }) {
    console.log(name); //return 'Google'
    console.log(age); //return 22
}

checkCompany(CompanyOne)

comments powered by Disqus