-
Notifications
You must be signed in to change notification settings - Fork 0
/
Extract-Fields-of-Function-in-Object-Destructuring.js
70 lines (58 loc) · 1.41 KB
/
Extract-Fields-of-Function-in-Object-Destructuring.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Extract Fields of Function in Object Destructuring
// Object
const mhs = {
id: 123,
nama: 'Gagak Rimang',
umur: 35,
email: 'gagakRimang@emails.com'
}
// Destructuring by using functions
function getId(mhs){
return mhs.id;
}
function getNama(mhs){
return mhs.nama;
}
function getValue(val){
return val;
}
function getItems({id, nama}){
return id + ', ' + nama;
}
// Default value - Individual Field
console.log(getId(mhs)); // output: 123
console.log(getNama(mhs)); // output: Gagak Rimang
console.log(getValue(mhs.id)); // output: 123
console.log(getValue(mhs.nama)); // output: Gagak Rimang
// Default Value - All Fields
console.log(getValue(mhs));
// output:
// {
// email: "gagakRimang@emails.com",
// id: 123,
// nama: "Gagak Rimang",
// umur: 35
// }
// Default Value - Multiple Fields
console.log(getItems(mhs)); // output: 123, Gagak Rimang
//------------------------------------------------------------------
// Extract fields by using .map method in Object Destructuring
// Object
const heroes = [
{ name: 'Batman', role: 'Good guy' },
{ name: 'Joker', role: 'Bad guy' }
];
// Destructuring
const player = heroes.map(
function({ name, role }) {
return name + ' as ' + role;
}
);
const names = heroes.map(
function({ name }){
return name;
}
);
// Result
console.log(player); // output: ["Batman as Good guy", "Joker as Bad guy"]
console.log(names); // output: ["Batman", "Joker"]