I found this to be the most elegant way. Also I believe JS-engines are heavily optimized for it.
use built in JSON.stringify(value[, replacer[, space]]) functionality. Docs are here.
Example is in context of retrieving some data from an external API, defining some model accordingly, get the result and chop of everything that couldn't be defined or unwanted:
function chop (obj, cb) {
const valueBlacklist = [''];
const keyBlacklist = ['_id', '__v'];
let res = JSON.stringify(obj, function chopChop (key, value) {
if (keyBlacklist.indexOf(key) > -1) {
return undefined;
}
// this here checks against the array, but also for undefined
// and empty array as value
if (value === null || value === undefined || value.length < 0 || valueBlacklist.indexOf(value) > -1) {
return undefined;
}
return value;
})
return cb(res);
}
In your implementation.
// within your route handling you get the raw object `result`
chop(user, function (result) {
var body = result || '';
res.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'application/json'
});
res.write(body);
// bang! finsihed.
return res.end();
});
// end of route handling