This article will demonstrate a few ways to omit properties from a javascript objects.

Recently I discovered that ES7(Ecma Script 7) has a really clever way of copying an object while omitting certain properties.

I thought I would quickly show how to do that, along with how to achieve the same results using lodash.

Let’s get into it.

With Lodash

1
2
3
4
5
6
import _ from 'lodash'
const animalObject = { 'bear': 1, 'snake': '2', 'cow': 3 };
 
const newObject = _.omit(animalObject, ['bear', 'cow']);

// newObject is:  { 'snake': '2' }

This is pretty nifty right? Lodash seems to have a method for everything.

With ES7

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

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

Pretty cool right? I was really surprised when I first saw this. I neve would have thought you could use object destructuring and the spread operator to omit properties from a javascript object.

Seeing cool programming tricks like this is what keeps programming fresh and interesting.

Please join the RemoteDevDaily mailing list if you want to see more cool tips and tricks like this.