JavaScript: How to serialize maps of maps of maps of ...

Recently I had to serialize a map in JavaScript. On the Internet I found code similar to this:

/* json-map.js */

export const replacer = (key, value) => {
  if(value instanceof Map) {
    return {
      dataType: 'Map',
      value: Array.from(value.entries()),
    };
  } else {
    return value;
  }
}

export const reviver = (key, value) => {
  if(typeof value === 'object' && value !== null) {
    if (value.dataType === 'Map') {
      return new Map(value.value);
    }
  }
  return value;
}
 

Now I had the problem that this works for maps of arrays, but not for maps of maps. I pondered over it for a while and then came up with a recursive solution that does not only work for maps of maps, but also for maps of maps of maps, maps of maps of maps of maps, and so on:

/* json-map.js */

export const replacer = (key, value) => {
  if(value instanceof Map) {
    return {
      dataType: 'Map',
      value: (value.entries() instanceof Map) ? replacer(value.key, value.entries()): Array.from(value.entries()),
    };
  } else {
    return value;
  }
}

export const reviver = (key, value) => {
  if(typeof value === 'object' && value !== null) {
    if (value.dataType === 'Map') {
      return new Map(value instanceof Map ? reviver(value.key, value.value) : value.value);
    }
  }
  return value;
}
  

Hope this help some of you! 

Adok 

Comments

Popular posts from this blog

Volko Hull - An Alternative to Convex Hull