m-o
A collection of functions that work on both Maps and Objects, letting you write code that can handle either, if that’s your M.O.
The functions are: has
, hasIn
, get
, getIn
, set
, edit
, delete
, construct
, reconstruct
, entries
, entriesArray
, keys
, keysArray
, values
, and valuesArray
.
Installation
Requires Node.js 7.0.0 or above.
npm install m-o --save
The module exports an object with multiple methods.
Usage
Nota Bene: Maps can accept keys of any type, but Objects cannot. If you expect your code to work with both, then you should only use strings/numbers/symbols as keys.
const mo = const map = const obj = {} // Setmomo // Hasmo // truemo // true // Getmo // 'world'mo // 'world' // vs. the normal way:map // 'world'objhello // 'world' // Editmomomo // 'world!'mo // 'world!' // Deletemo // truemo // truemo // falsemo // false // Entriesmo // MapIteratormo // ArrayIterator // Construct a Map or an Object, depending on the class providedconst entries = 'hello' 'world'mo // {hello: 'world'}mo // Map {}mo // XMap // Construct a new Map or Object having the same class as an existing objectmo // {hello: 'world'}mo // Mapmo // XMap
Entries, Keys, and Values
The Map
prototype has entries()
, keys()
, and values()
methods which return iterators, whereas the global functions Object.entries()
, Object.keys()
, and Object.values()
return arrays. The m-o
module lets you remain consistent regardless of which type you’re dealing with. Use the entries()
, keys()
, and values()
methods if you want iterators, and use entriesArray()
, keysArray()
, and valuesArray()
if you want arrays.
Accessing Prototype Properties
By default, has
and get
treat an object like a dictionary and therefore only access its own properties. If you want to access object prototype properties as well, use the hasIn
or getIn
methods instead. (With Maps, behavior is the same regardless of which set of methods you use.)
typeof objtoString // 'function'typeof mo // 'undefined'typeof mo // 'function' mo // falsemo // true