This is a question similar to How to remove undefined and null values from an object using lodash?. However, the solutions proposed there do not conserve the constructor. In add
You can use JSON.stringify()
, JSON.parse()
, RegExp.prototype.test()
JSON.parse(JSON.stringify(obj, function(a, b) {
if (!/^_/.test(a) && b === undefined) {
return null
}
return /^_/.test(a) && !b ? void 0 : b
}).replace(/null/g, '"undefined"'));
var obj = {key1 : 'value1', key2 : {key21 : 'value21', _key22: undefined}, key3: undefined, _key4 : undefined}
var res = JSON.stringify(obj, function(a, b) {
if (!/^_/.test(a) && b === undefined) {
return null
}
return /^_/.test(a) && !b ? void 0 : b
}).replace(/null/g, '"undefined"');
document.querySelector("pre").textContent = res;
res = JSON.parse(res);
console.log(res)