Skip to content

Instantly share code, notes, and snippets.

@tekaratzas
Last active July 21, 2017 19:40
Show Gist options
  • Save tekaratzas/5b544a6838777e412e3eb9b0a360fb37 to your computer and use it in GitHub Desktop.
Save tekaratzas/5b544a6838777e412e3eb9b0a360fb37 to your computer and use it in GitHub Desktop.
Different Ways of iterating through lists.
// Adding a property to the global Object => all objects inherit from this. ex: toString method and prototype.
Object.prototype.WTF = "this should not be in your object";
function a() {
this.unwanted = 10;
this.crap = "dhjbjbfdjbf";
}
function child() {
this.a = 1;
this.b = 2;
}
//child inherits from a
child.prototype = new a();
var obj = new child();
for (var property in obj) { // Not only is this slower than Object.keys, but it also contains the parent properties
console.log(property + ": " + obj[property]);
}
for (var property in obj) { // This will return the proper keys but it is still 50% slower than Object.keys
if(obj.hasOwnProperty(property))
console.log(property + ": " + obj[property]);
}
Object.keys(obj).map((e) => console.log(`key=${e} value=${obj[e]}`)); // best way !
Object.entries(obj).forEach(([key, value]) => console.log(`key=${key} value=${value}`)); // this one is good too!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment