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*/
1Object.keys(obj).forEach(function(key) {
2 console.log(key, obj[key]);
3});
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});
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*/
1const obj = {
2 a: "aa",
3 b: "bb",
4 c: "cc",
5};
6//This for loop will loop through all keys in the object.
7// You can get the value by calling the key on the object with "[]"
8for(let key in obj) {
9 console.log(key);
10 console.log(obj[key]);
11}
12
13//This will return the following:
14// a
15// aa
16// b
17// bb
18// c
19// cc
1Add thisvar p = {
2 "p1": "value1",
3 "p2": "value2",
4 "p3": "value3"
5};
6
7for (var key in p) {
8 if (p.hasOwnProperty(key)) {
9 console.log(key + " -> " + p[key]);
10 }
11}