TypeOfNaN

How to Select or Omit Properties From an Object in JavaScript

Nick Scialli
October 18, 2020

New — Check out my free newsletter on how the web works!

Selecting or omitting properties from a JavaScript object is a fairly common problem without a built-in solution. In this post, we’re going to roll our own pick and omit utility functions to help us accomplish these goals.

Selecting Properties from an Object

If we want to select any number of properties from a JavaScript object, we can implement the following pick function:

function pick(obj, ...props) {
  return props.reduce(function (result, prop) {
    result[prop] = obj[prop];
    return result;
  }, {});
}

Let’s see this in action! Our first argument to the pick function will be the object we want to pick from and the subsequent arguments will the the names of the keys we want to keep.

const person = {
  name: 'Pete',
  dog: 'Daffodil',
  cat: 'Omar',
};

const dogPerson = pick(person, 'name', 'dog');

console.log(dogPerson);
// { name: "Pete", dog: "Daffodil" }

We see that by providing the person object as the first argument and then the strings "name" and "dog" as the subsequent arguments, we’re able to retain the "name" and "dog" props from our object while disregarding the "cat" prop.

Omitting Properties From an Object

If we want to omit any number of properties from a JavaScript object, we can implement the following omit function:

function omit(obj, ...props) {
  const result = { ...obj };
  props.forEach(function (prop) {
    delete result[prop];
  });
  return result;
}

Again, let’s use the same person object to see this in action.

const person = {
  name: 'Pete',
  dog: 'Daffodil',
  cat: 'Omar',
};

const catPerson = omit(person, 'dog');

console.log(catPerson);
// { name: "Pete", cat: "Omar" }

We can see that, by providing our person object as the first argument and the string "dog" as the second argument, we’re able to get a new object with the "dog" property omitted!

🎓 Learn how the web works

Over my 20 year career in tech, I have noticed that an often-neglected part of interview prep is learning to explain technical concepts clearly. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that you can use in your interview prep (or just to gain a better understanding of the web).

Enter your email below to get started. It's free and you can unsubscribe at any time. You won't regret it!

Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli