Skip to content

Instantly share code, notes, and snippets.

@kodejuice
Last active July 23, 2022 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kodejuice/54e2770cfa10e517aadfb57fcc249cb2 to your computer and use it in GitHub Desktop.
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
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