Skip to content

Instantly share code, notes, and snippets.

@aoberoi
Last active December 30, 2017 22:31
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 aoberoi/eb76dd543e559ae5f04b574147f88f44 to your computer and use it in GitHub Desktop.
Save aoberoi/eb76dd543e559ae5f04b574147f88f44 to your computer and use it in GitHub Desktop.
JavaScript objects as key-value pairs or dictionaries

Cheatsheet for JavaScript objects as key-value pairs (object literals)

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.

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