Last active
July 23, 2022 20:32
-
-
Save kodejuice/54e2770cfa10e517aadfb57fcc249cb2 to your computer and use it in GitHub Desktop.
Iterate over JavaScript objects like its a Map, with the for...of statement
This file contains hidden or 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
Object.prototype[Symbol.iterator] = function* (){ | |
let c = 0; | |
const [key, values] = [Object.keys(this), Object.values(this)]; | |
while (c < keys.length) { | |
yield [keys[c], values[c++]] | |
} | |
} | |
// usage | |
let obj = { | |
name: "kodejuice", | |
site: "github" | |
} | |
for (let [key, value] of obj) { | |
console.log(`${key} = ${value}`); | |
} | |
// name = kodejuice | |
// site = github | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment