-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathiterate-over-objects.js
76 lines (61 loc) · 2.82 KB
/
iterate-over-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
/*
------------------------------------------------------------------------------------
Tutorial: Javascript Object Iteration
------------------------------------------------------------------------------------
*/
// There are several ways to approach iteration over objects in JS, the for…in loop decidedly the most popular with the widest support among older browsers. The for...in will iterate over every property in the object, as long as the key isn't a Symbol. Take the following:
var testObj = { firstName: 'Jane',
lastName: 'Doe',
email: '[email protected]',
title: 'CEO',
age: 45
};
// The for..in loop looks like this:
// for (const prop in testObj) {
// statement goes here
// }
// 'prop' can be named anything, it is a variable that a property is assigned to in each iteration (ie, firstName, lastName etc). 'testObj' will be the name of the object being iterated over.
for (const prop in testObj) {
console.log(`${prop}: ${testObj[prop]}`);
}
//In the above example, we can view the key with 'prop', and the value with 'testObj[prop]'. Expected Output:
// "firstName: Jane"
// "lastName: Doe"
// "email: [email protected]"
// "title: CEO"
// "age: 45"
//If you want to access a specific property, a conditional can be used:
for (const prop in testObj) {
if( prop === 'email') {
console.log(testObj[prop]);
}
} //Expected output: "[email protected]"
/*
------------------------------------------------------------------------------------
Challenge 1: Create a new object with multiple properties. Try to access a specific property similar to the example above.
------------------------------------------------------------------------------------
/*
/*
------------------------------------------------------------------------------------
Challenge 2: Take the following objects *within* the 'people' object. Knowing what you know about accessing object properties and iterating over an object using the method above, how would you access and console.log each email address?
------------------------------------------------------------------------------------
*/
var people = {
id1: {
firstName: 'Jane',
lastName: 'Doe',
email: '[email protected]',
title: 'CEO',
age: 45},
id2: {
firstName: 'John',
lastName: 'Smith',
email: '[email protected]',
title: 'Director',
age: 36
}
};
//Expected Output:
//Hint: people.id1.email or people.['id1']['email'] will access the specified objects email. The same dot notation can be applied to the 'people' object and it's properties using the for...in loop