1// object to loop through
2let obj = { first: "John", last: "Doe" };
3
4// loop through object and log each key and value pair
5//ECMAScript 5
6Object.keys(obj).forEach(function(key) {
7 console.log(key, obj[key]);
8});
9
10//ECMAScript 6
11for (const key of Object.keys(obj)) {
12 console.log(key, obj[key]);
13}
14
15//ECMAScript 8
16Object.entries(obj).forEach(
17 ([key, value]) => console.log(key, value)
18);
19
20// OUTPUT
21/*
22 first John
23 last Doe
24*/
1// Looping through arrays created from Object.keys
2const keys = Object.keys(fruits)
3for (const key of keys) {
4 console.log(key)
5}
6
7// Results:
8// apple
9// orange
10// pear
11
1var obj = { first: "John", last: "Doe" };
2
3Object.keys(obj).forEach(function(key) {
4 console.log(key, obj[key]);
5});
1var person={
2 first_name:"johnny",
3 last_name: "johnson",
4 phone:"703-3424-1111"
5};
6for (var property in person) {
7 console.log(property,":",person[property]);
8}