Skip to content

Instantly share code, notes, and snippets.

@AnsonH
Last active September 8, 2021 11:17
Show Gist options
  • Save AnsonH/02304468042c9d64e11a22f0f7dc699c to your computer and use it in GitHub Desktop.
Save AnsonH/02304468042c9d64e11a22f0f7dc699c to your computer and use it in GitHub Desktop.
Javascript Tip #2 - 3 ways to iterate through object keys
/* 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);
}
@AnsonH
Copy link
Author

AnsonH commented Sep 8, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment