1const students = {
2 adam: {age: 20},
3 kevin: {age: 22},
4};
5
6Object.entries(students).forEach(student => {
7 // key: student[0]
8 // value: student[1]
9 console.log(`Student: ${student[0]} is ${student[1].age} years old`);
10});
11/* Output:
12Student: adam is 20 years old
13Student: kevin is 22 years old
14*/
1const obj = {
2 name: 'Jean-Luc Picard',
3 rank: 'Captain'
4};
5
6// Prints "name Jean-Luc Picard" followed by "rank Captain"
7Object.keys(obj).forEach(key => {
8 console.log(key, obj[key]);
9});
1const obj = {
2 name: 'Jean-Luc Picard',
3 rank: 'Captain'
4};
5
6// Prints "name Jean-Luc Picard" followed by "rank Captain"
7Object.entries(obj).forEach(entry => {
8 const [key, value] = entry;
9 console.log(key, value);
10});
1const list = {
2 key: "value",
3 name: "lauren",
4 email: "lauren@notreally.com",
5 age: 30
6};
7
8// Object.keys returns an array of the keys
9// for the object passed in as an argument.
10
11Object.keys(list).forEach(val => {
12 let key = val;
13 let value = list[val];
14 console.log(`${key} : ${value}`);
15});
16
17// Returns:
18// "key : value"
19// "name : lauren";
20// "email : lauren@notreally.com"
21// "age : 30"
22
1/* Answer to: "foreach object javascript" */
2
3const games = {
4 "Fifa": "232",
5 "Minecraft": "476"
6 "Call of Duty": "182"
7};
8
9Object.keys(games).forEach((item, index, array) => {
10 let msg = `There is a game called ${item} and it has sold ${games[item]} million copies.`;
11 console.log(msg);
12});
13
14/*
15 The foreach statement can be used in many ways and with object can make
16 development a lot easier.
17
18 A link for for more information on this can be found below and in the source:
19 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
20*/
1function logArrayElements(element, index, array) {
2 console.log('a[' + index + '] = ' + element)
3}
4
5// Notice that index 2 is skipped, since there is no item at
6// that position in the array...
7[2, 5, , 9].forEach(logArrayElements)
8// logs:
9// a[0] = 2
10// a[1] = 5
11// a[3] = 9
12