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});
1var obj = {
2 first: "John",
3 last: "Doe"
4};
5
6//
7// Visit non-inherited enumerable keys
8//
9Object.keys(obj).forEach(function(key) {
10
11 console.log(key, obj[key]);
12
13});
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 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 object1 = {
2 a: 'somestring',
3 b: 42
4};
5for (let [key, value] of Object.entries(object1)) {
6 console.log(`${key}: ${value}`);
7}
8// expected output:
9// "a: somestring"
10// "b: 42"
11// order is not guaranteed