Showing posts with label Destructuring. Show all posts
Showing posts with label Destructuring. Show all posts

Monday, April 16, 2018

Object destructuring

We can use destructuring assignment for objects also.

Syntax:
let {var1, var2} = {var1:…, var2:…}

Right side is an existing object which that we want to split into variables. Left side is our pattern to split variables.

Basic Example I:



let options = {
  title: "MasterPage",
  width: 100,
  height: 200
};

let {title, width, height} = options;

alert(title);  // MasterPage
alert(width);  // 100
alert(height); // 200

Internally its uses like , options.title, options.width and options.height. Hope you got it.
and order does not matter here. Anywhere it will work.

Example II:



let options = {
  title: "MasterPage",
  height: 200,
  width: 100
};

let {title, width, height} = options;

alert(title);  // MasterPage
alert(width);  // 100
alert(height); // 200

Above order was changed, still its working perfectly.

Rest Operator:

Below we have used Rest operator with object. So other than title, remaining will come under rest. See below code.


let options = {
  title: "MasterPage",
  height: 200,
  width: 100
};

let {title, ...rest} = options;

// now title="MasterPage", rest={height: 200, width: 100}
alert(rest.height);  // 200
alert(rest.width);   // 100







Destructuring assignment

We all know, most used data structures in JavaScript are Object and Array.

Destructuring asis a special syntax that allows us to “unpack” arrays or objects into a bunch of variables.

Why its allowing? Since they are more convenient. Most of the time we want to work with complex functions that have a lot of parameters, default values etc.,

Array destructuring:



let arr = ["Ilakiya", "Kannika"]

// destructuring assignment
let [firstName, surname] = arr;

alert(firstName); // Ilakiya
alert(surname);  // Kannika

See, Its very compatible. Its coming with ES6.

Here is another trick for ignoring first elements. See below...


let [, , title] = ["Test1", "Test2", "Test3", "Test4"];

alert( title ); // Test3

As you have put comma for two times, first two elements not considered here.

You can more play with this.. See below.


let user = {};
[user.name, user.surname] = "Ilyakiya My Love".split(' ');

alert(user.name); // Ilyakiya


Rest ...

You can mention multiple at a time , then go with “the rest” using three dots "..."


let [name1, name2, ...rest] = ["Test1", "Test2", "Test10", "Test11"];

alert(name1); // Test1
alert(name2); // Test2

alert(rest[0]); // Test10
alert(rest[1]); // Test11
alert(rest.length); // 2