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.
// Render a todo list that updates in realtimevar todosEl = document.getElementById('todos')gun.get('todos').map().on(function(todo, id){ var li = document.getElementById(id) || document.createElement('li') li.id = id li.textContent = todo.text if(todo.done){ li.style.textDecoration = 'line-through' } if(!li.parentNode){ todosEl.appendChild(li) }})
// Iterate over users and their postsgun.get('users').map().on(function(user, userId){ console.log('User:', user.name) gun.get('users').get(userId).get('posts').map().on(function(post){ console.log(' Post:', post.title) })})
// Only match keys starting with 'user:'gun.get('data').map({'.' : 'user:*'}).on(function(user){ console.log('User:', user)})// Match specific patterngun.get('events').map({'.' : /2024-.*/}).on(function(event){ console.log('2024 event:', event)})
// Map over empty set does nothinggun.get('emptySet').map().on(function(item){ // Never called if set is empty})// To detect empty setsvar found = falsegun.get('mySet').map().once(function(){ found = true})setTimeout(function(){ if(!found){ console.log('Set is empty') }}, 100)
// Reusable map referencevar allTodos = gun.get('todos').map()// Use it multiple timesallTodos.once(function(todo){ console.log('Todo:', todo)})allTodos.on(function(todo){ updateUI(todo)})// Both callbacks receive the same data