Last active
September 8, 2021 11:17
-
-
Save AnsonH/02304468042c9d64e11a22f0f7dc699c to your computer and use it in GitHub Desktop.
Javascript Tip #2 - 3 ways to iterate through object keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Tweet: https://twitter.com/AnsonH_/status/1435562848399228936?s=20 */ | |
const student = { name: "Tom", age: 20, gender: "male" }; | |
// Method 1: for-in loop | |
for (const key in student) { | |
console.log(key + ": " + student[key]); | |
} | |
// Method 2: Object.keys() | |
Object.keys(student).forEach(key => { | |
console.log(key + ": " + student[key]); | |
}) | |
// Method 3: Object.entries() | |
for (let [key, value] of Object.entries(student)) { | |
console.log(key + ": " + value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Further links:
Object.keys()
Object.entries()