Skip to content

Instantly share code, notes, and snippets.

@nichoth
Created August 4, 2024 05:46
Show Gist options
  • Save nichoth/7ce114a0723a73efa82310df965cfd74 to your computer and use it in GitHub Desktop.
Save nichoth/7ce114a0723a73efa82310df965cfd74 to your computer and use it in GitHub Desktop.
JSON + Set & Map

JSON + Set & Map

Serialize + deserialize sets and maps. See this blog post.

function replacer(key, value) {
  if (value instanceof Map) {
    return { __type: 'Map', value: Object.fromEntries(value) }
  }
  if (value instanceof Set) {
    return { __type: 'Set', value: Array.from(value) }
  }
  return value
}

function reviver(key, value) {
  if (value?.__type === 'Set') { 
    return new Set(value.value) 
  }
  if (value?.__type === 'Map') { 
    return new Map(Object.entries(value.value)) 
  }
  return value
}

const obj = { set: new Set([1, 2]), map: new Map([['key', 'value']]) }
const str = JSON.stringify(obj, replacer)
const newObj = JSON.parse(str, reviver)
// { set: new Set([1, 2]), map: new Map([['key', 'value']]) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment