← Back to list

Safely Omitting Properties in JavaScript: A Custom omit Function

Custom implementation of the omit method of lodash.

Deep Shah in Stackademic · 2025-01-06 03:56 · 0 claps · 3.9 min read
#javascript #nested #lodash #omit
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Safely Omitting Properties in JavaScript: A Custom omit Function

Custom implementation of the omit method of lodash.

Hello, beautiful people on the internet.

Imagine you’re working with a large JavaScript object, and you want to remove some specific properties — perhaps user details, or sensitive information. The challenge comes when the properties are deeply nested, and you need a safe and efficient way to remove them without breaking your app.

In this article, we’ll explore how to safely omit properties from objects using a custom omit function.

The Problem with Removing Nested Properties

When working with deeply nested objects, you may want to remove specific properties. For instance, suppose you have a complex object like a user profile, and you want to remove the user’s address or some other nested data. If one of the properties is missing, trying to delete it directly will throw an error.

Let’s say you want to remove user.address.city. If address or city doesn’t exist, trying to access them will result in an error, breaking your app. To solve this, you need a safe way to delete properties, even if they are deeply nested.

What Can We Do About It?

This is where the custom omit function comes in. It allows you to safely omit properties from deeply nested objects, ensuring that your app won’t break if a property doesn’t exist.

Custom omit Function: How It Works

The omit function works in two stages:

  1. Omit a Single Property: The omitObject function removes a property from an object or array at a specified path.
  2. Omit Multiple Properties: The main omit function can handle multiple paths, removing each one from the object.

Here’s the code for the custom omit function:

const omitObject = (obj, path) => {
  // check valid object
  if(typeof(obj) !== 'object' || object === null){
    return;
  }

  // parse the string and convert [] notation to dot notation
  // and then convert it to the array so it'll be easy to traverse
  // through every property
  if(typeof(path) === 'string' || path instanceof String){
    path = path
      .replaceAll('[', '.') // to get the '.' ahead of all properties
      .replaceAll(']', '') // remove unnecessary ]
      .replace(/\.{2,}/g, '.') // replace multiple dots with a single dot
      .replace(/^\./, '') // remove leading dot
      .replace(/\.$/, '') // remove trailing dot
      .split('.'); // convert to the array with dot as a seperator
  }

  // if we are at the last key, then delete it
  if(path.length === 1){
    // if last key is array, delete the required index
    // else delete the object property
    if(Array.isArray(obj)){
      obj.splice(path[0], 1)
    } else {
      delete obj[path[0]];
    }
  }

  // if key exists
  if(obj.hasOwnProperty(path[0])){
    omitObject(obj[path[0]], path.slice(1));
  }

  return obj;
}

// in this case, we'll have multiple paths for the object
// paths => string|string[]
const omit = (obj, paths) => {
  // if string is passed, then convert it to an array
  if(typeof(paths) === 'string' || paths instanceof String){
    paths = [paths];
  }

  // delete properties from object for every path
  paths.forEach(path => {
    obj = omitObject(obj, path);
  });
  return obj;
}

Breaking It Down:

  1. Object Validation: The function first checks if the object (obj) is valid—i.e., it’s not null and is of type object.
  2. Path Conversion: If the path is a string (like 'a[0].b.c'), it converts it into an array format (['a', '0', 'b', 'c']) to make it easier to traverse. This also handles cases like bracket notation ([0]), multiple dots (a..b), and leading/trailing dots.
  3. Deleting the Property: If the path reaches the last key, the function deletes the property. If the property is part of an array, it uses splice to remove the element at the specified index. If it’s part of an object, it uses the delete operator.
  4. Recursion: If the path hasn’t reached the last key, the function recursively navigates deeper into the object to omit the property at the specified path.

Example object:-

let object = {
  a: [
    { b: { c: 3 } },
    { d: [1, 2] }
  ],
  e: null,
  f: undefined,
  g: { h: 'value' }
};

// Omitting a nested property
console.log(omit(object, 'a[0].b.c')); 
// Result: { a: [{ b: {} }, { d: [1, 2] }], e: null, f: undefined, g: { h: 'value' } }

Edge Cases Our omit Function Handles

1. Omitting a Property in an Array

If you want to omit a property from an array element, you can do it like this:

console.log(omit(object, 'a[1].d')); 
// Result: { a: [{ b: { c: 3 } }], e: null, f: undefined, g: { h: 'value' } }

2. Omitting a Top-Level Property

To remove a top-level property, simply specify its path:

console.log(omit(object, 'e')); 
// Result: { a: [{ b: { c: 3 } }], f: undefined, g: { h: 'value' } }

3. Omitting a Non-Existent Property

If the property doesn’t exist, there’s no effect:

console.log(omit(object, 'z')); 
// Result: { a: [{ b: { c: 3 } }], e: null, f: undefined, g: { h: 'value' } }

4. Omitting Multiple Properties at Once

You can omit multiple properties in one go by passing an array of paths:

console.log(omit(object, ['e', 'f'])); 
// Result: { a: [{ b: { c: 3 } }], g: { h: 'value' } }

I’m always looking to improve and would love to hear your thoughts! If you have any suggestions, feedback, or topics you’d like me to cover, please feel free to share them in the comments below. Your insights are greatly appreciated! 🙂

Thank you for being a part of the community

Before you go:


메타데이터
post_id
f0508fdda403
slug
safely-omitting-properties-in-javascript-a-custom-omit-function-f0508fdda403
url
https://blog.stackademic.com/safely-omitting-properties-in-javascript-a-custom-omit-function-f0508fdda403
canonical_url
https://blog.stackademic.com/safely-omitting-properties-in-javascript-a-custom-omit-function-f0508fdda403
author_url
https://medium.com/@deepshah1358
status
ok
fetched_at
2026-06-26 21:52:29