Skip to content

Instantly share code, notes, and snippets.

@akhawaja
Created February 28, 2019 03:49
Show Gist options
  • Save akhawaja/78712e7ea246cdf7269b0d723e042460 to your computer and use it in GitHub Desktop.
Save akhawaja/78712e7ea246cdf7269b0d723e042460 to your computer and use it in GitHub Desktop.
JSON-to-Map and Map-to-JSON converter.
/**
* Convert a Map to a JSON object.
*
* @param {Map<any, any>} map - The Map to convert to JSON.
* @returns {Object} The converted JSON object.
*/
const mapToJson = (map) => {
let obj = Object.create(null)
for (let [key, val] of map) {
obj[key] = val
}
return obj
}
/**
* Convert a JSON object to a Map.
*
* @param {Object} obj - The JSON object to convert.
* @returns {Map<any, any>} The converted Map.
*/
const jsonToMap = (obj) => {
let map = new Map()
for (let key of Object.keys(obj)) {
map.set(key, obj[key])
}
return map
}
module.exports = {
mapToJson,
jsonToMap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment