From 89810386ae04f6aa81bedd8c04d7db215efcfaff Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Thu, 16 Jun 2022 15:46:56 +0300 Subject: [PATCH] Add map-object conversions --- snippets/mapToObject.md | 22 ++++++++++++++++++++++ snippets/objectToMap.md | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 snippets/mapToObject.md create mode 100644 snippets/objectToMap.md diff --git a/snippets/mapToObject.md b/snippets/mapToObject.md new file mode 100644 index 000000000..0dd4adfd0 --- /dev/null +++ b/snippets/mapToObject.md @@ -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} +``` diff --git a/snippets/objectToMap.md b/snippets/objectToMap.md new file mode 100644 index 000000000..76eb54473 --- /dev/null +++ b/snippets/objectToMap.md @@ -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} +```