Filter object for allowed keys

By Hunter Becton on May 13, 2022

export const filterObject = (obj, ...allowedKeys) => {
  const newObj = {};
  Object.keys(obj).forEach((el) => {
    if (allowedKeys.includes(el)) newObj[el] = obj[el];
  });
  return newObj;
};

How to use

The first argument in this function is the JavaScript object that you want to filter. The rest of the values passed in are comma-separated string values of the keys that you want to allow in the returned object. These key values will be spread into an array by the ...allowedKeys spread syntax.

For example, let's say you have the following request body come in for an API route to update a user: { name: 'John Doe', email: 'test@example.com', role: 'ADMIN' } . The name and email keys are the only keys that are allowed, so you can use this function to filter out all the other keys like so: filterObject(req.body, 'name', 'email') , which will return the following object: { name: 'John Doe', email: 'test@example.com' }.