-
Notifications
You must be signed in to change notification settings - Fork 0
/
8. Objects.js
109 lines (80 loc) · 1.75 KB
/
8. Objects.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
objects are referenced type
objects store key value pairs
objects don't have index
keys are always in strings
*/
key = "gender"
value = "male"
person = {
name : "Asad",
age : 24,
// computed values
[key] : value
}
// access
for(p in person){
p, ':', person[p]
}
// array iterator of keys
Object.keys(person)
// array iterator of values
Object.values(person)
// array iterator of [keys and values]
for([key, value] of Object.entries(ticket))
console.log(key,value)
// ------------------
// clone objects
obj1 = {
key1 : "value1",
key2 : "value2"
}
obj2 = {
key3 : "value1",
key4 : "value2"
}
// spread operator
obj3 = {...obj1, ...obj1, key69: "value69"}
// old method using assign
obj4 = Object.assign({}, obj1)
// ----------------
// spread string into object
newobj = {..."Hello"}
// spread array into object
newobj = {...["asad", "ali"]}
// -----------------
// object destructuring
// variable with key names
var {name, age, ...rest} = person
// variable with different names
var {name: pname, age: year, ...rest} = person
// -----------------
// objects inside array
users = [
{id: 1, name: 'asad'},
{id: 2, name: 'shaheen'},
{id: 3, name: 'maira'}
]
for(user of users)
user.name
// ----------------
// nested destructuring
var [user1, user2] = users
var [{id}, , {name}] = users
var [{name: myname}] = users
var [{name: myname, id}] = users
// ----------------
// parameter destructuring
function print({name, age}){
console.log(name, age)
}
print(person)
// -----------------
// optional chaining
person?.address
// -----------------
// method (function inside objects)
person.about = function(){
console.log(`hi i'm ${this.name}`)
}
person.about()