Omit Matching Object Keys

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of omitting object keys based on a given condition using JavaScript. We will learn how to use the omitBy() function to filter out keys from an object based on a provided function. Through practical examples, we will understand how this function can be useful in simplifying our code and making it more efficient.


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-28528{{"`Omit Matching Object Keys`"}} javascript/data_types -.-> lab-28528{{"`Omit Matching Object Keys`"}} javascript/arith_ops -.-> lab-28528{{"`Omit Matching Object Keys`"}} javascript/comp_ops -.-> lab-28528{{"`Omit Matching Object Keys`"}} javascript/array_methods -.-> lab-28528{{"`Omit Matching Object Keys`"}} javascript/higher_funcs -.-> lab-28528{{"`Omit Matching Object Keys`"}} javascript/destr_assign -.-> lab-28528{{"`Omit Matching Object Keys`"}} end

Removing Object Keys Based on Callback Function

To remove object keys based on a callback function, use omitBy function.

  • omitBy creates an object consisting of properties that return falsy for the given function.
  • Object.keys() and Array.prototype.filter() are used to remove keys for which fn returns a truthy value.
  • Array.prototype.reduce() converts the filtered keys back to an object with the corresponding key-value pairs.
  • The callback function takes two arguments: value and key.
  • The example below shows how omitBy is used to remove numeric keys from an object.
const omitBy = (obj, fn) =>
  Object.keys(obj)
    .filter((k) => !fn(obj[k], k))
    .reduce((acc, key) => ((acc[key] = obj[key]), acc), {});

omitBy({ a: 1, b: "2", c: 3 }, (x) => typeof x === "number"); // { b: '2' }

Summary

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

Other JavaScript Tutorials you may like