# Maps

Map store can be used to store objects with one level of depth and change keys in this object.

To create map store call `map(initial)` function with initial object.

```ts
import { map } from 'nanostores'

export const $profile = map({
  name: 'anonymous'
})
```

In TypeScript, you can pass type parameter with store’s type:

```ts
export interface ProfileValue {
  name: string
  email?: string
}

export const $profile = map<ProfileValue>({
  name: 'anonymous'
})
```

`store.set(object)` or `store.setKey(key, value)` methods will change the store.

```ts
$profile.setKey('name', 'Kazimir Malevich')
```

Setting `undefined` will remove optional key:

```ts
$profile.setKey('email', undefined)
```

Store’s listeners will receive third argument with changed key.

```ts
$profile.listen((profile, oldProfile, changed) => {
  if (changed) console.log(`${changed} new value ${profile[changed]}`)
})
```

You can also listen for specific keys of the store being changed, using `listenKeys` and `subscribeKeys`.

```ts
listenKeys($profile, ['name'], (value, oldValue, changed) => {
  console.log(`$profile.Name new value ${value.name}`)
})
```

Nested mutations can be listened to using a base key. For example, listening to `user` will trigger on `user.name` mutations:

```ts
// Mutating user.name triggers the listener
listenKeys($state, ['user'], (value, oldValue, changed) => {
  console.log(`user changed: ${changed}`)
})
```

`subscribeKeys(store, keys, cb)` in contrast with `listenKeys(store, keys, cb)` also call listeners immediately during the subscription. Please note that when using subscribe for store changes, the initial evaluation of the callback has undefined old value and changed key.

***

*Imported from the [Nano Stores README](https://github.com/nanostores/nanostores/blob/1.5.5/README.md#maps) for version 1.5.5. Improve this page there.*
