-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectMethods.js
More file actions
84 lines (66 loc) · 1.67 KB
/
ObjectMethods.js
File metadata and controls
84 lines (66 loc) · 1.67 KB
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
// JavaScript Object keys, values, entries methods
// Why are these useful?
const nameAndAge = {
'John': 30,
'Jane': 25,
'Mary': 18,
'Peter': 35,
'Ruslan': 26,
'Alexandera': 29,
}
// Objects are not iterable
for (const key in nameAndAge) {
console.log(key);
}
// 1) Object.keys()
// - Takes 1 argument, an object.
// - Returns an array of keys contained in the object you pass into Object.keys().
const nameAndAge2 = {
'Ruslan': 26,
'Alexandera': 29,
'John': 30,
'Jane': 25,
'Mary': 18,
'Peter': 35,
}
const names = Object.keys(nameAndAge2);
console.log(names);
// Iterating over the returned keys directly
for (const key of Object.keys(nameAndAge2)) {
console.log(key);
}
// 2) Object.values()
// - Takes 1 argument, an object.
// - Returns an array of values contained in the object you pass into Object.values().
const nameAndAge3 = {
'Ruslan': 26,
'Alexandera': 29,
'John': 30,
'Jane': 25,
'Mary': 18,
'Peter': 35,
}
const values = Object.values(nameAndAge3);
console.log(values);
// Iterating over the returned values directly
for (const value of Object.values(nameAndAge3)) {
console.log(value);
}
// 3) Object.entries()
// - Takes 1 argument, an object.
// - Returns an array of arrays containing [key, value] pairs
// contained in the object you pass into Object.entries().
const nameAndAge4 = {
'Ruslan': 26,
'Alexandera': 29,
'John': 30,
'Jane': 25,
'Mary': 18,
'Peter': 35,
}
const entries = Object.entries(nameAndAge4);
console.log(entries);
// More advanced use using destructuring
for (const [key, value] of Object.entries(nameAndAge4)) {
console.log(key, value);
}