How to omit specific properties from an object in JavaScript

Is there a clean way to return a new object that omits certain properties that the original object contains without having to use something like lodash?


const { bar, baz, ...qux } = foo

Now your object qux has all of the properties of foo except for bar and baz.


If you know the list of the properties that you want preserved as well as omitted, the following "whitelisting" approach should work:

const exampleFilter = ({ keepMe, keepMeToo }) => ({ keepMe, keepMeToo })

console.log(
  exampleFilter({
    keepMe: 'keepMe',
    keepMeToo: 'keepMeToo',
    omitMe: 'omitMe',
    omitMeToo: 'omitMeToo'
  })
)

In modern environments you can use this code snippet:

function omit(key, obj) {
  const { [key]: omitted, ...rest } = obj;
  return rest;
}

const {omittedPropertyA, omittedPropertyB, ...remainingObject} = originalObject;

Explanation:

With ES7

you could use object destructuring and the spread operator to omit properties from a javascript object:

const animalObject = { 'bear': 1, 'snake': '2', 'cow': 3 };
 
const {bear, ...other} = animalObject

// other is: { 'snake': '2', 'cow:'  3}

source: https://remotedevdaily.com/two-ways-to-omit-properties-from-a-javascript-object/