In many JavaScript programs, plain objects are used as a hash map, a dictionary, or as a simple set of key-value pairs. JavaScript properties can be a little tricky, so this cheatsheet maps out options for accessing those enumerable properties. Non-enumerable properties are usually not interesting in this usage (this includes methods, constructor, etc).
Own Properties | Own & Prototype Properties | |
---|---|---|
Exists? | x.propertyIsEnumerable(name) |
Requires walking up the prototype chain |
As a collection | Object.keys(x) (or Object.entries(x) if working with values too) |
Requires walking up the prototype chain |
Iterate | Object.keys(x).forEach() (or Object.entries(x).forEach() if working with values too)* |
for (let k in x) { /* ... */ } |
* for...of
is better for iterating over true "collection" types, such as Array, String, Set, Map, etc.