1const hero = {
2 name: 'Batman',
3 realName: 'Bruce Wayne'
4};
5
6const { name, realName } = hero;
7
8name; // => 'Batman',
9realName; // => 'Bruce Wayne'
1//simple example with object------------------------------
2let obj = {name: 'Max', age: 22, address: 'Delhi'};
3const {name, age} = obj;
4
5console.log(name);
6//expected output: "Max"
7
8console.log(age);
9//expected output: 22
10
11console.log(address);
12//expected output: Uncaught ReferenceError: address is not defined
13
14// simple example with array-------------------------------
15let a, b, rest;
16[a, b] = [10, 20];
17
18console.log(a);
19// expected output: 10
20
21console.log(b);
22// expected output: 20
23
24[a, b, ...rest] = [10, 20, 30, 40, 50];
25
26console.log(rest);
27// expected output: Array [30,40,50]
1// destructuring object & nested object & combine object into single object
2let user = {
3 name: 'Mike',
4 friend: ["John", "Paul", "Jimmy"],
5 location: {
6 region:"England",
7 country:"United Kingdom"
8 },
9 aboutMe: {
10 status: "Single",
11 pet: "Dog",
12 }
13}
14
15const { name, friend, location, aboutMe: {status , pet} } = user;
16
17console.log(name); // output: "Mike"
18console.log(friend); // output: [ 'John', 'Paul', 'Jimmy' ]
19console.log(location); // output: { region: 'England', country: 'United Kingdom' }
20console.log(status); // output: "Single"
21console.log(pet); // output: "Dog"
22
23//Combining Obj
24const newUser = {
25 ...user,
26 car: {
27 make: "Buick",
28 year: 2012,
29 }
30}
31
32console.log(newUser)
33// output user obj + car object into one
34// {
35// name: 'Mike',
36// friend: [ 'John', 'Paul', 'Jimmy' ],
37// location: { region: 'England', country: 'United Kingdom' },
38// aboutMe: { status: 'Single', pet: 'Dog' },
39// car: { make: 'Buick', year: 2012 }
40// }
41
42//Bonus destructuring from object of array
43const {friend: [a, ...b]} = user
44console.log(a) // output: "John"
45console.log(b) // output: ["Paul", "Jimmy"]
1const book = {
2 title: 'Ego is the Enemy',
3 author: 'Ryan Holiday',
4 publisher: {
5 name: 'Penguin',
6 type: 'private'
7 }
8};
9
10const {title: bookName = 'Ego', author, name: {publisher: { name }} = book, type: {publisher: { type }} = book } = book;
1const objA = {
2 prop1: 'foo',
3 prop2: {
4 prop2a: 'bar',
5 prop2b: 'baz',
6 },
7};
8
9// Deconstruct nested props
10const { prop1, prop2: { prop2a, prop2b } } = objA;
11
12console.log(prop1); // 'foo'
13console.log(prop2a); // 'bar'
14console.log(prop2b); // 'baz'
1({ a, b } = { a: 10, b: 20 });
2console.log(a); // 10
3console.log(b); // 20
4
5
6// Stage 4(finished) proposal
7({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
8console.log(a); // 10
9console.log(b); // 20
10console.log(rest); // {c: 30, d: 40}
11