JavaScript: Convert Object to/from Map

By Xah Lee. Date: . Last updated: .

Object to Map

Here is a function that converts object to map data type.

/* [
xah_obj_to_map(obj) convert obj to map datatype.
Return a map instance. The variable obj is not changed.
Only keys converted are: own property, enumerable, string keys.
Version 2018-02-02
] */
const xah_obj_to_map = ((obj) => {
  const mp = new Map();
  Object.keys(obj).forEach((k) => {
    mp.set(k, obj[k]);
  });
  return mp;
});

// xah_obj_to_map2 same as xah_obj_to_map, but require JS2017
const xah_obj_to_map2 = ((obj) => {
  return new Map(Object.entries(obj));
});

// HHH___________________________________________________________________
// test

const ob = { "a": 2, "b": 9, [Symbol()]: "symbol" };

console.log(xah_obj_to_map(ob));
// Map { 'a' => 2, 'b' => 9 }

console.log(xah_obj_to_map2(ob));
// Map { 'a' => 2, 'b' => 9 }

[see Access Property]

[see Symbol Tutorial]

Map to Object

Object.fromEntries

JavaScript Map Object

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc