Last Updated: February 25, 2016
·
1.087K
· 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"}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside