Skip to content

Instantly share code, notes, and snippets.

@RoyalIcing
Last active September 27, 2023 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RoyalIcing/b03f63532d73551b895bdada537efe31 to your computer and use it in GitHub Desktop.
Save RoyalIcing/b03f63532d73551b895bdada537efe31 to your computer and use it in GitHub Desktop.
Parsing JSON to Map
// Hard to read nested arrays.
const c = new Map([['a', 1], ['b', 2]])
console.log(c)
// Have to write using object wrapped in two layers of calls.
const d = new Map(Object.entries({ a: 1, b: 2}))
console.log(d)
let a = JSON.stringify({ a: { b: 2, c: 3 }, d: [4, 5] })
let b = JSON.parse(a, (key, value) => {
if (typeof value === "object" && !Array.isArray(value)) {
return new Map(Object.entries(value))
} else {
return value
}
})
console.log(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment