Add map-object conversions

This commit is contained in:
Chalarangelo
2022-06-16 15:46:56 +03:00
parent 65e2ece57f
commit 89810386ae
2 changed files with 44 additions and 0 deletions

22
snippets/mapToObject.md Normal file
View File

@ -0,0 +1,22 @@
---
title: Convert Map to object
shortTitle: Map to object
tags: object
expertise: intermediate
author: chalarangelo
cover: blog_images/succulent-1.jpg
firstSeen: 2022-06-16T05:00:00-04:00
---
Converts a `Map` to an object.
- Use `Map.prototype.entries()` to convert the `Map` to an array of key-value pairs.
- Use `Object.fromEntries()` to convert the array to an object.
```js
const mapToObject = map => Object.fromEntries(map.entries());
```
```js
mapToObject(new Map([['a', 1], ['b', 2]])); // {a: 1, b: 2}
```

22
snippets/objectToMap.md Normal file
View File

@ -0,0 +1,22 @@
---
title: Convert object to Map
shortTitle: Object to Map
tags: object
expertise: intermediate
author: chalarangelo
cover: blog_images/succulent-2.jpg
firstSeen: 2022-06-16T05:00:00-04:00
---
Converts an object to a `Map`.
- Use `Object.entries` to convert the object to an array of key-value pairs.
- Use the `Map` constructor to convert the array to a `Map`.
```js
const objectToMap = obj => new Map(Object.entries(obj));
```
```js
objectToMap({a: 1, b: 2}); // Map {'a' => 1, 'b' => 2}
```