How do I preserve undefined values when doing JSON.stringify(hash)?
Here\'s an example:
var hash = {
\"name\" : \"boda\",
\"email\" : undefined,
function stringifyWithUndefined(obj, space) {
const str = JSON.stringify(obj, (key, value) => value === undefined ? '__undefined__' : value, space);
return str.replace(/"__undefined__"/g, 'undefined');
}
Example:
const obj = {
name: 'boda',
email: undefined,
country: 'africa'
};
console.log(stringifyWithUndefined(obj, 2));
Result:
{
"name": "boda",
"email": undefined,
"country": "africa"
}