@mgwalker/serializable-map
v1.0.1
Published
An extension of the native Map object that attempts to serialize to JSON
Readme
Serializable map
The native Javascript Map object does not have a toJSON() method.
That's fine, but what if you need to serialize an object whose keys
need to be dynamically computed? Eg.,
class TimedKey {
toJSON() {
return new Date().toISOString();
}
}
const o = {
[new TimedKey()]: "the current time",
};Plain object keys must be strings. If you create an object key that is not a string, it is stringified immediately. As a result, in the above example, the key would be the time when the object was created, not the time when the object was serialized.
This is true for any key whose serialized value is computed. Is this a kind of niche use case? You betcha. But it's one that exists.
import SerializableMap from "@mgwalker/serializable-map";
class TimedKey {
toJSON() {
return new Date("2019-07-22T17:52:03Z").toISOString();
}
}
const map = new SerializableMap();
map.set(new TimedKey(), "timed key");
console.log(JSON.stringify(map));
// {
// "2019-07-22T17:52:03.000Z": "timed key",
// }
setTimeout(() => {
console.log(JSON.stringify(map));
// Notice that the seconds in the key have gone up
// by thirty! Hooray!
//
// {
// "2019-07-22T17:52:33.000Z": "timed key",
// }
}, 30_000);And if you have an existing plain object that you want to treat like a map that you want to serialize later, there's a helper for that, too.
import SerializableMap from "@mgwalker/serializable-map";
const map = SerializableMap.fromObj({
key: "value",
list: [
"yep",
{
these: "work",
},
"recursively",
],
});Credit
I originally created this library for the National Weather Service.
Contributing
As an original work of the US Government, the initial code is not subject to copyright. In the spirit of public domain software, this repo also explicitly adopts the CC0 statement. Contributors agree that their contributions are committed to the public domain, and in jurisdictions that do not have public domain, are otherwise bound to the terms of the CC0 license.
