How Lodash _.map Handles JavaScript Map Objects
In the Lodash utility library, _.map handles native
JavaScript ES6 Map objects fundamentally differently than
standard arrays or plain objects. Rather than unpacking the internal
key-value entries stored in the Map, Lodash treats the
Map instance as a generic non-array object. Consequently,
the iteratee does not execute over the Map entries at all,
executing only over any enumerable object properties manually assigned
to the instance itself.
The Collection Detection Mechanism
When _.map receives a collection, it determines
iteration behavior by evaluating isArrayLike(collection). A
native JavaScript Map instance defines a .size
property rather than a numeric .length property, causing
isArrayLike to return false.
Because it fails the array-like check, Lodash routes the
Map through its internal object iteration path
(baseForOwn), which inspects the object using standard
property enumeration methods equivalent to
Object.keys().
Internal Slots vs. Enumerable Properties
A JavaScript Map stores its entries in private internal
slots accessed via methods such as .set(),
.get(), and the [Symbol.iterator] protocol.
These entries are not own enumerable string or symbol properties of the
Map object:
- Entry Bypassing: Because internal entries are not
enumerable properties, Lodash's property scanner finds zero keys. The
iteratee function is executed zero times, and
_.map(myMap, iteratee)evaluates to an empty array[]. - Ad-hoc Property Execution: If enumerable properties
are assigned directly to the
Mapobject (such asmyMap.customProp = 'value'),_.mapexecutes the iteratee on those specific properties instead. In this scenario, the iteratee receives(value, key, collection), wherekeyis the property name string rather than any key managed viamyMap.set().
Differences from Native Map Iteration
Lodash's execution model contrasts sharply with both native
Map.prototype.forEach and standard array mapping:
- Native
Map.prototype.forEach: Executes its callback for every entry withcallback(value, key, map), preserving entry types and ignoring arbitrary non-entry properties. - Lodash
_.mapon Arrays and Objects: Unpacks values and keys/indices automatically, callingiteratee(value, index|key, collection). - Lodash
_.mapon Converted Maps: If theMapis converted to an iterable array viaArray.from(myMap)or[...myMap],_.mapiterates over arrays of entries. In this state, the iteratee receives(entry, index, array), whereentryis a two-element array[key, value], rather than distinctvalueandkeyparameters.