.map()
The.map() method iterates over all properties in a collection, calling a callback for each item. It’s essential for working with sets, lists, and any object with dynamic keys.
Signature
Parameters
Experimental: Function called for each item to transform the data.Signature:
function(data, key, message, event)data- The item datakey- The item’s key/IDmessage- Full message objectevent- Event control object
- Return the data to pass it through unchanged
- Return modified data to transform it
- Return
undefinedto filter out the item - Return a GUN reference to chain to it
Lexical filter object to match specific keys
Return Value
Returns a GUN chain that emits each item individually. Chain with.on() or .once() to process items.
Examples
Basic Iteration
Realtime List Rendering
Nested Maps
Transform with Callback (Experimental)
Lexical Filtering
Chat Application
Count Items
Filter and Sort
Implementation Details
From the source code (map.js:16-37):.map() method:
- Creates a new chain that listens for all child updates
- Fires the chain callback for each property/item
- Optionally filters using lexical matching
- Experimental: transforms data when callback is provided
- Automatically follows links to nested data
Map vs Iteration
| Feature | .map() | .get(key) |
|---|---|---|
| Purpose | Iterate all items | Access specific item |
| Keys | Dynamic/unknown | Known |
| Usage | Collections, sets | Single values |
| Returns | Chain per item | Single chain |
Performance Considerations
Empty Sets
Reuse Map Chain
Notes
.map()without arguments returns a chain for iteration- Use
.once()after.map()for one-time iteration - Use
.on()after.map()for realtime updates - The callback version (with function argument) is experimental
- Map automatically resolves links to the linked data
- No guaranteed iteration order - items arrive as they’re loaded
- For empty collections, callbacks never fire
- Map is perfect for working with
.set()collections