keys-iterator
Returns an iterator of the keys/indexes of an Object, Map, Array, or Typed Array. Useful for when you need the keys of a collection object but aren’t sure what type of collection you’ll be given.
Installation
Requires Node.js 6.0.0 or above.
npm i keys-iterator
API
The module exports a single function.
Parameters
- Bindable:
c
(Array, iterator, Object, Map, Set, string, or Typed Array) - Object argument:
- Optional:
arrays
/maps
/sets
(array, class, or string): A class that should be treated as equivalent toArray
/Map
/Set
(respectively), the string name of such a class, or an array of such classes/strings. - Optional:
inObj
(boolean): Whether or not to act like the “in” operator by including inherited Object property keys. Only takes effect ifc
is an Object (i.e. not another recognized type). Defaults tofalse
. - Optional:
reflectObj
(boolean): Whether or not to use reflection to include non-enumerable Object property keys. Only takes effect ifc
is an Object (i.e. not another recognized type). Defaults tofalse
.
- Optional:
Return Value
An iterator which yields keys from the collection.
Examples
Arrays
const keys = const i = inextvalue // 0inextvalue // 1inextdone // true // Supports the bind operator'a' 'b'::
Iterators
keys-iterator
will treat an iterator as if it were an array of values. Each “key” will be an incrementing integer index that starts at zero.
const keys = { 'a' 'b'} const i = inextvalue // 0inextvalue // 1inextdone // true
Maps
const keys = const map = map const i = inextvalue // 'key'inextdone // true
Objects
const keys = const i = inextvalue // 'key'inextdone // true // Supports the bind operatorconst obj = key: 'value'obj::
Inherited Object Properties
Include Object property keys from the prototype chain by setting inObj
to true
:
const keys = {}Clsprototypekey = 'value' const i = inextvalue // 'key'inextdone // true
Non-Enumerable Object Properties
Include non-enumerable Object property keys by setting reflectObj
to true
:
const keys = const obj = {}Object const i = inextvalue // 'key'inextdone // true
Sets
keys-iterator
will treat a Set like an array, and will yield integer index keys starting at zero. Note that this behavior is different from that of the built-in Set.prototype.keys()
method.
const keys = const set = setset const i = inextvalue // 0inextvalue // 1inextdone // true
Strings
keys-iterator
will treat a string like a character array, and will yield integer index keys starting at zero.
const keys = const i = inextvalue // 0inextvalue // 1inextdone // true
Typed Arrays
const keys = const typedArray = 4 const i = inextvalue // 0inextdone // true