skip to Main Content

I build some records in a database table. When I show it to users, some fields I don’t want to show. This is an example: https://aircode.cool/icm3kf2jje

// @see https://docs.aircode.io/guide/functions/
const {db} = require('aircode');

module.exports = async function (params, context) {
    const table = db.table('persons');

    if(!(await table.where().findOne())) {
        const students = [];
        for(let i = 0; i < 100; i++) {
            students.push({
                name: `students${i}`, 
                score: Math.floor(Math.random() * 100), 
                info: {_private: 'something', public: {_foo: 'foo', bar: 'bar'}}
            });
        }
        await table.save(students);
    }
    const result = await table.where({score: db.gt(60)}).limit(10).find();
  return {
   result,
  };
};

I don’t want to show the fields which name starts with an underscore, like info:_private and info:public:_foo.

How can I easily filter out such unwanted fields in result?

In this case, I can only filter these fields one by one:

for(const [k, v] in result) {
    delete v.info._private;
    delete v.info.public._foo;
}

Is there a better way to efficiently and universally accomplish this task?

2

Answers


  1. you can check if the key starts with ‘_’

    Object.keys(your_obj).forEach(k => {
       if(k.startsWith('_')) delete your_obj[k];
    })
    
    Login or Signup to reply.
  2. Try lodash omit, it is a cleaner way to maintain the keys that you want to exclude.

    https://lodash.com/docs/#omit

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search