-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop_over.js
More file actions
44 lines (37 loc) · 1.02 KB
/
loop_over.js
File metadata and controls
44 lines (37 loc) · 1.02 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
// How to loop over an object in JavaScript?
const object = {
propOne: 'one',
propTwo: 'two',
propThree: 'three',
propFour: 'four'
}
// Error - You can't use for...of directly on an object
// Use for...in for keys
for (const key in object) {
console.log(key);
}
// You can also use for...in to iterate over values by accessing the object's properties
for (const key in object) {
const value = object[key];
console.log(key);
console.log(value);
}
// Object.keys() to iterate over keys
for (const key of Object.keys(object)) {
console.log(key);
}
// Object.values() to iterate over values
for (const value of Object.values(object)) {
console.log(value);
}
// Object.entries() to iterate over key-value pairs
for (const [key, value] of Object.entries(object)) {
console.log(key);
console.log(value);
}
// You can also use array methods like map to get an array of values
const values = Object.values(object).map((value) => {
console.log(value);
return value;
});
console.log(values);