Last Updated: February 25, 2016
·
678
· johannesboyne

Object attribute & mongoDB field hider

ever wanted to dynamically hide fields from objects (plain JS or mongoDB results)?
https://gist.github.com/johannesboyne/4715413

// this is used to work in Node.js
// if you want to use it inside the browser, replace the map function to ensure older browser support.
// DEPENDENCIES: underscore!
function omitFields (model, hidden_fields) {  
    var hider_code = 'return _.omit(model';
    hidden_fields.map(function (hider) {
        hider_code += ', \''+hider+'\'';
    });
    hider_code += ');';

    return new Function('_', 'model', hider_code)(_, model);
}

// use
omitFields({name: "Mr. Johnson", password: "PWHASH", secret: "mystery"}, ['password', 'secret']);
// => return: {name: "Mr. Johnson"}