Created
February 28, 2019 03:49
-
-
Save akhawaja/78712e7ea246cdf7269b0d723e042460 to your computer and use it in GitHub Desktop.
JSON-to-Map and Map-to-JSON converter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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