Last active
May 12, 2022 13:48
-
-
Save yvele/f115f7dd0ed849f918f38b134ec3598a to your computer and use it in GitHub Desktop.
`JSON.stringify` and `JSON.parse` that preserves nested undefined values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Serialize a POJO while preserving `undefined` values. | |
*/ | |
function serializePOJO(value, undefinedPlaceholder = "[undefined]") { | |
const replacer = (key, value) => (value === undefined ? undefinedPlaceholder : value); | |
return JSON.stringify(value, replacer); | |
} | |
/** | |
* Deserialize a POJO while preserving `undefined` values. | |
*/ | |
function deserializePOJO(value, undefinedPlaceholder = "[undefined]") { | |
const pojo = JSON.parse(value); | |
if (pojo === undefinedPlaceholder) { | |
return undefined; | |
} | |
// Function that walks through nested values | |
function deepIterate(value, callback, parent, key) { | |
if (typeof value === "object" && value !== null) { | |
Object.entries(value).forEach(([entryKey, entryValue]) => deepIterate(entryValue, callback, value, entryKey)); | |
} else if (Array.isArray(value)) { | |
value.forEach((itemValue, itemIndex) => deepIterate(itemValue, callback, value, itemIndex)); | |
} else if (parent !== undefined) { | |
callback(value, parent, key); | |
} | |
} | |
// https://jsfiddle.net/76y0mudk/5/ | |
deepIterate(pojo, (value, parent, key) => { | |
if (value === undefinedPlaceholder) { | |
parent[key] = undefined; | |
} | |
}); | |
return pojo; | |
} | |
const source = { | |
foo : undefined, | |
bar : { | |
baz : undefined, | |
qux : [1, undefined, 2] | |
} | |
}; | |
const serialized = serializePOJO(source); | |
console.log("Serialized", serialized); | |
const deserialized = deserializePOJO(serialized); | |
console.log("Deserialized", deserialized); | |
// See also https://stackoverflow.com/a/72216472/1480391 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment