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.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
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}
1for (var key in validation_messages) {
2 // skip loop if the property is from prototype
3 if (!validation_messages.hasOwnProperty(key)) continue;
4
5 var obj = validation_messages[key];
6 for (var prop in obj) {
7 // skip loop if the property is from prototype
8 if (!obj.hasOwnProperty(prop)) continue;
9
10 // your code
11 alert(prop + " = " + obj[prop]);
12 }
13}