1//destructuring array
2const alphabet = ['a', 'b', 'c', 'b', 'e'];
3const [a, b] = alphabet;
4console.log(a, b);
5//Expected output: a b
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;
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"]
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
1const hero = {
2 name: 'Batman',
3 realName: 'Bruce Wayne',
4 address: {
5 city: 'Gotham'
6 }
7};
8
9// Object destructuring:
10const { realName, address: { city } } = hero;
11city; // => 'Gotham'