Skip to content

Instantly share code, notes, and snippets.

@alik472
Created May 19, 2019 18:51
Show Gist options
  • Save alik472/3303c8c195f51fbaf56e0de9cf8ff469 to your computer and use it in GitHub Desktop.
Save alik472/3303c8c195f51fbaf56e0de9cf8ff469 to your computer and use it in GitHub Desktop.
JS Days Part 5 - object methods iterations

-Object properties can be own (the property is on the object itself) or inherited (not on the object itself, on one of its prototypes).

-Object properties can be enumerable or non-enumerable. Non-enumerable properties are left out of lots of property enumerations/arrays.

-Property names can be strings or Symbols. Properties whose names are Symbols are left out of lots of property enumerations/arrays.

-Here in 2018, your options for looping through an object's properties are (some examples follow the list):

  1. for-in [MDN, spec] — A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings
  2. Object.keys [MDN, spec] — A function providing an array of the names of an object's own, enumerable properties whose names are strings.
  3. Object.values [MDN, spec] — A function providing an array of the values of an object's own, enumerable properties.
  4. Object.entries [MDN, spec] — A function providing an array of the names and values of an object's own, enumerable properties (each entry in the array is a [name, value] array).
  5. Object.getOwnPropertyNames [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.
  6. Object.getOwnPropertySymbols [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.
  7. Reflect.ownKeys [MDN, spec] — A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.

If you want all of an object's properties, including non-enumerable inherited ones, you need to use a loop and Object.getPrototypeOf [MDN, spec] and use Object.getOwnPropertyNames, Object.getOwnPropertySymbols, or Reflect.ownKeys on each object in the prototype chain (example at the bottom of this answer). With all of them except for-in, you'd use some kind of looping construct on the array (for, for-of, forEach, etc.).

https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object

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