Omit Object Keys

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring how to use the omit function in JavaScript to remove specific key-value pairs from an object. We will learn how to use Object.keys(), Array.prototype.filter() and Array.prototype.includes() to filter out the provided keys, and how to use Array.prototype.reduce() to create a new object with the remaining key-value pairs. This lab is a great way to practice working with objects in JavaScript and to learn how to selectively manipulate them.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Remove Keys from Object

To remove specific keys from an object, use the omit function which takes an object and an array of keys to remove.

  • The Object.keys() method is used to get all the keys of the object
  • The Array.prototype.filter() method is then used to remove the specified keys from the list of keys
  • Finally, Array.prototype.reduce() is used to create a new object with the remaining key-value pairs
const omit = (obj, keysToRemove) =>
  Object.keys(obj)
    .filter((key) => !keysToRemove.includes(key))
    .reduce((newObj, key) => {
      newObj[key] = obj[key];
      return newObj;
    }, {});

Example usage:

omit({ a: 1, b: "2", c: 3 }, ["b"]); // { 'a': 1, 'c': 3 }

Summary

Congratulations! You have completed the Omit Object Keys lab. You can practice more labs in LabEx to improve your skills.