1Object.entries(obj).forEach(
2 ([key, value]) => console.log(key, value)
3);
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
1const object = { a: 1, b: 2, c: 3 };
2
3for (const property in object) {
4 console.log(`${property}: ${object[property]}`);
5}