DEV Community

Discussion on: My Tooling Wishes for 2020 ✨

Collapse
 
mfulton26 profile image
Mark Fulton

You can use a reviver with JSON.parse to actually create Map instances instead of plain objects when parsing JSON so that you can use Map.prototype.has instead of Object.prototype.hasOwnProperty:

JSON.parse('{"a":null,"b":{"c":[0,1]}}', (_, value) =>
  value !== null && typeof value === "object" && !Array.isArray(value)
    ? new Map(Object.entries(value))
    : value
);
// ▸ Map(2) {"a" => null, "b" => Map(1)}

You can then also use a replacer with JSON.stringify to stringify Map instances as plain objects:

JSON.stringify(
  new Map([
    ["a", null],
    ["b", new Map([["c", [0, 1]]])]
  ]),
  (_, value) => (value instanceof Map ? Object.fromEntries(value) : value)
);
// "{"a":null,"b":{"c":[0,1]}}"