JavaScript: Convert Object to/from Map ð
Convert Object to Map (no require JS2015)
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; }); // ssss--------------------------------------------------- // test const xx = { "a": 2, "b": 9, [Symbol()]: "symbol" }; console.log(xah_obj_to_map(xx)); // Map { "a" => 2, "b" => 9 }
Convert Object to Map (require JS2017)
// 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)); }); const xx = { "a": 2, "b": 9, [Symbol()]: "symbol" }; console.log(xah_obj_to_map2(xx)); // Map { "a" => 2, "b" => 9 }
Map to Object
Here's a function to convert map object to data object.
/* [ xah_map_to_obj convert a map object to map, require just ES2015. This assumes the map key are string or symbol, because object key can only be these types. http://xahlee.info/js/js_Object.fromEntries.html Version 2020-12-12 ] */ const xah_map_to_obj = ((xiterable) => { const xout = {}; for (let [k, v] of xiterable) xout[k] = v; return xout; }); // ssss--------------------------------------------------- // test const xx = new Map([["a", 3], ["b", 4]]); const jj = xah_map_to_obj(xx); console.log(jj); // { a: 3, b: 4 }