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*/
1let obj = {
2 key1: "value1",
3 key2: "value2",
4 key3: "value3"
5}
6
7Object.keys(obj).forEach(key => {
8 console.log(key, obj[key]);
9});
10// key1 value1
11// key2 value2
12// key3 value3
13
14// using for in - same output as above
15for (let key in obj) {
16 let value = obj[key];
17 console.log(key, value);
18}
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});
1/Example 1: Loop Through Object Using for...in
2// program to loop through an object using for...in loop
3
4const student = {
5 name: 'John',
6 age: 20,
7 hobbies: ['reading', 'games', 'coding'],
8};
9
10// using for...in
11for (let key in student) {
12 let value;
13
14 // get the value
15 value = student[key];
16
17 console.log(key + " - " + value);
18}
19
20/Output
21 name - John
22 age - 20
23 hobbies - ["reading", "games", "coding"]
24
25//If you want, you can only loop through the object's
26//own property by using the hasOwnProperty() method.
27
28if (student.hasOwnProperty(key)) {
29 ++count:
30}
31
32/////////////////////////////////////////
33
34/Example 2: Loop Through Object Using Object.entries and for...of
35// program to loop through an object using for...in loop
36
37const student = {
38 name: 'John',
39 age: 20,
40 hobbies: ['reading', 'games', 'coding'],
41};
42
43// using Object.entries
44// using for...of loop
45for (let [key, value] of Object.entries(student)) {
46 console.log(key + " - " + value);
47}
48/Output
49 name - John
50 age - 20
51 hobbies - ["reading", "games", "coding"]
52
53//In the above program, the object is looped using the
54//Object.entries() method and the for...of loop.
55
56//The Object.entries() method returns an array of a given object's key/value pairs.
57//The for...of loop is used to loop through an array.
58
59//////////////////////////////////////////////////////////