JavaScript: Convert Object to Map Data Type

By Xah Lee. Date: . Last updated: .

Object to Map

Here's a function that converts object to map data type.

〔►see JavaScript: Symbol Tutorial

// xah_obj_to_map(obj) converts obj to map datatype.
// Returns the map instance. The variable obj is not changed. Only keys converted are: own property, enumerable, string keys.
// version 2017-02-09
const xah_obj_to_map = ( obj => {
    let mp = new Map;
    Object.keys ( obj ). forEach (k => { mp.set(k, obj[k]) });
    return mp;
});

// test

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

〔►see JavaScript: Access Property, List Properties

Map to Object

Here's a function that converts map to object data type.

// xah_map_to_obj ( myMap ) converts map instance myMap to object datatype.
// Returns the new object. myMap is not changed.
// Assume keys are strings. If not, they are converted implicitly to string
// version 2017-02-09
const xah_map_to_obj = ( aMap => {
    let obj = {};
    aMap.forEach ((v,k) => { obj[k] = v });
    return obj;
});

// test
let mm = new Map([["a", 1], ["b", 2], ["c", 3]]);
console.log ( xah_map_to_obj (mm) );
// { a: 1, b: 2, c: 3 }

Map Topic

  1. JavaScript: the Map Object Tutorial
  2. JavaScript: Map Object
  3. JavaScript: Map.prototype
  4. JavaScript: Iterate Over Map Object
  5. JavaScript: Convert Object to Map Data Type
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.