Omit Object Keys

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28529{{"`Omit Object Keys`"}} javascript/data_types -.-> lab-28529{{"`Omit Object Keys`"}} javascript/arith_ops -.-> lab-28529{{"`Omit Object Keys`"}} javascript/comp_ops -.-> lab-28529{{"`Omit Object Keys`"}} javascript/array_methods -.-> lab-28529{{"`Omit Object Keys`"}} javascript/higher_funcs -.-> lab-28529{{"`Omit Object Keys`"}} javascript/destr_assign -.-> lab-28529{{"`Omit Object Keys`"}} end

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.

Other JavaScript Tutorials you may like