Skip to Content
  • Website
Codsen
  • Home
  • Open Source
  • Articles
  • About

prevOpen Source→object-delete-keynext

object-delete-key4.2.5

Delete keys from all arrays or plain objects, nested within anything, by key or by value or by both, and clean up afterwards. Accepts wildcards.

Downloads per monthChangelogMIT Licenselibera manifesto
  • the top
  • Installation
  • Quick Take
  • Examples
  • PURPOSE
  • API — DELETEKEY()
  • SELECTOR BEHA…
  • OPTIONS
  • WILDCARD MAT…
  • SUPPORTED TRE…
  • CLEANUP
  • PROGRESS AND…
  • INVALID INPUT
  • API — DEFAULTS
  • API — TYPES
  • API — VERSION
  • Changelog

No 3rd party dependencies. All dependencies and devDependencies, checked recursively, are Codsen packages.

Permalink to InstallationInstallation

Permalink to Quick TakeQuick Take

Permalink to ExamplesExamples

  • Deletion by the key only
  • Deletion by the value only
  • Delete null and undefined object values
  • Disable the cleanup which would otherwise happen after deletion
  • Delete only when both the key and value match
  • Delete matching object keys without deleting matching array values
  • Compose progress and inspect completion statistics
  • Wildcards

Purpose

object-delete-key returns a cloned tree with matching object properties or array elements removed. It can select object properties by key, value, or both, accepts whole-string wildcard patterns, and can prune empty containers left on a deletion path.

If you need to delete a whole nested object because it contains a matching key/value pair, use ast-delete-object instead.

API — deleteKey()

The main function deleteKey() is imported like this:

The function takes exactly two required arguments:

Input argumentTypeRequiredDescription
input
Type: Supported tree value
inputSupported tree valueyesValue to clone, search, delete from, and optionally clean.
opts
Type: Opts selector object
optsOpts selector objectyesSelector plus cleanup and reporting options.

It returns MutableTree<T>: the same logical root category as input, with the requested entries removed. Array and object results are independent clones. Primitive roots are valid no-op inputs and are returned unchanged. The original input and a structured val selector are not mutated.

const input = {
  keep: true,
  remove: true,
  nested: { remove: true },
};

deleteKey(input, { key: "remove" });
// => { keep: true }

// input is unchanged

An explicit null or undefined root is valid. Omitting the first argument is an error.

Selector behavior

At least one own selector field must be present. An own val: undefined is a real value selector, not an omitted option. key: null is the legacy marker for an absent key selector and is valid only when val is also present.

Object properties and array elements retain the package’s established, asymmetric selector behavior:

Parent container{ key }{ val }{ key, val }
Object
ObjectMatch the property nameMatch the valueBoth must match
Array
ArrayMatch the element value; this is the legacy meaningNo direct array matchNo direct array match

Nested arrays and objects are still traversed in every mode. For example, a value-only selector can match an object property inside an array even though it does not directly select an array element.

deleteKey(
  {
    objectValue: undefined,
    list: [undefined, "remove", "keep"],
  },
  { val: undefined },
);
// => { list: [undefined, "remove", "keep"] }

deleteKey(["remove", "keep"], { key: "remove" });
// => ["keep"]

Use only to restrict a match by its parent container. It does not change what key and val mean.

Options

KeyTypeRequiredDefaultDescription
key
Type: String
Default: absent
keyStringunless val is presentabsentObject-key pattern or legacy array-element pattern.
val
Type: Supported tree value
Default: absent
valSupported tree valueunless key is a stringabsentObject-value pattern. An explicit undefined counts as present.
cleanup
Type: Boolean
Default: true
cleanupBooleannotruePrune affected containers that become strictly empty.
only
Type: Only
Default: "any"
onlyOnlyno"any"Restrict direct matches to array or object parents.
reportCompletionFunc
Type: Function or null
Default: null
reportCompletionFuncFunction or nullnonullReceive frozen completion statistics after a successful call.
reportProgressFunc
Type: Function or null
Default: null
reportProgressFuncFunction or nullnonullReceive finite, monotonic progress values during the transformation.
reportProgressFuncFrom
Type: Finite number
Default: 0
reportProgressFuncFromFinite numberno0Set the first value in a caller-composable progress range.
reportProgressFuncTo
Type: Finite number
Default: 100
reportProgressFuncToFinite numberno100Set the final value; it cannot be below the start.

The Only type lists all supported aliases. Runtime matching trims surrounding whitespace and ignores letter case, then normalizes every alias to "array", "object", or "any".

Passing explicit undefined for cleanup, only, a reporting callback, or a range endpoint uses that field’s default. In contrast, an own key: undefined is invalid because selector presence must not be ambiguous.

The options argument must be a plain object. Ordinary cross-realm objects and null-prototype options objects are accepted. Unknown own keys, symbol keys, and invalid field values are rejected; inherited fields are ignored.

Wildcard matching

String selectors are case-sensitive whole-string patterns. * matches zero or more Unicode code points, including line breaks. A backslash escapes the next character, so \* matches a literal asterisk and \\ matches a literal backslash. Other punctuation is literal.

A leading ! negates that string pattern. For example, { key: "!draft*" } selects object keys other than those beginning with draft. Write \! to match a literal leading exclamation mark.

Nested strings in array or object val patterns use the same wildcard syntax. Structured values are compared strictly, including ordered array contents; their wildcard strings do not turn the surrounding structure into a loose subset match. NaN matches NaN. Other primitive values use their ordinary JavaScript equality behavior.

Supported trees

The input and a structured val selector can contain:

  • strings, numbers, Booleans, null, and undefined;
  • ordinary native arrays, including holes and explicit undefined elements; and
  • ordinary object-literal plain objects from the current or another realm.

Object fields must be own, enumerable, string-keyed data properties. Array indices must also be own data properties; extra array properties are not part of the supported grammar. An own __proto__ key is preserved as data without changing the result’s prototype.

Cycles, repeated container references, accessors, symbol or non-enumerable object fields, extra or out-of-range array properties, custom and null prototypes, class instances, functions, bigint, and symbol values are rejected. Validation does not invoke accessor getters.

Sparse holes stay sparse when no earlier element is deleted. Deleting an array element compacts that array once, shifting later values and holes by the usual array-deletion semantics. Natural NaN, infinities, signed zero, null, and explicit undefined remain data unless the selector intentionally matches them.

Traversal uses bounded call-stack space, so deeply nested supported trees do not fail merely because of recursion depth.

Cleanup

With cleanup: true, the function prunes a container only when a deletion affected that branch and the container is now strictly empty. It does not sweep unrelated pre-existing empty branches.

Strict emptiness means zero-length strings and arrays or objects recursively containing only strictly empty values. Whitespace is content. Array holes, undefined, null, Booleans, and numbers are also content. The root container is returned as {} or [] when emptied; it is never removed.

Set cleanup: false to remove direct matches while retaining empty containers.

const input = { nested: { remove: true } };

deleteKey(input, { cleanup: false, key: "remove" });
// => { nested: {} }

deleteKey(input, { cleanup: true, key: "remove" });
// => {}

Progress and completion reports

reportProgressFunc receives the configured start value, monotonic intermediate values, and the configured end value. Use reportProgressFuncFrom and reportProgressFuncTo when deletion is one stage of a larger operation. Equal start and end values are valid; an overflowing range span is not.

reportCompletionFunc runs once after a successful result is known and receives a frozen plain object:

KeyDescription
directDeletions
directDeletionsObject properties and array elements removed by the selector.
cleanupPrunedContainers
cleanupPrunedContainersAffected non-root containers removed because cleanup found them empty.
maxDepth
maxDepthDeepest validated entry, with the root value at depth 0.
totalEntries
totalEntriesValidated object properties and array slots, including holes.
visitedEntries
visitedEntriesObject properties and array slots visited during transformation.
timeTakenInMilliseconds
timeTakenInMillisecondsBest-effort, finite, non-negative elapsed time.

Callback exceptions are ignored and cannot change deletion results. Clock failures, backward clocks, and unusable differences report an elapsed time of 0. A call that fails validation emits neither progress nor completion reports.

const progress = [];
let completion;

const result = deleteKey(
  { keep: true, nested: { remove: true } },
  {
    key: "remove",
    reportProgressFunc(value) {
      progress.push(value);
    },
    reportProgressFuncFrom: 20,
    reportProgressFuncTo: 80,
    reportCompletionFunc(stats) {
      completion = stats;
    },
  },
);

// result === { keep: true }
// progress[0] === 20
// progress[progress.length - 1] === 80
// completion.directDeletions === 1
// completion.cleanupPrunedContainers === 1

Invalid input

Invalid calls throw a package-owned Error, TypeError, or RangeError. Every public validation message starts with object-delete-key/deleteKey(): [THROW_ID_XX]. This includes missing selectors, invalid options, unsupported selector values, and unsupported input trees.

API — defaults

You can import defaults:

It's a plain object:

The main function calculates the options to be used by merging the options you passed with these defaults.

The exported defaults snapshot is frozen and read-only. It is metadata, not global configuration: attempts to mutate it cannot change later calls. The snapshot contains key: null and val: undefined, but every call still needs an own key or val selector.

Here are all defaults in one place for copying:

API — types

This TypeScript package exports recursive read-only input types, mutable result types, selector and reporting types, and the legacy Obj alias:

TypeDescription
TreePrimitive
Type: TreePrimitive
TreePrimitiveSupported primitive leaves.
ReadonlyTreeValue
Type: ReadonlyTreeValue
ReadonlyTreeValueRecursive read-only input or selector value.
ReadonlyTreeArray
Type: ReadonlyTreeArray
ReadonlyTreeArrayRead-only array branch.
ReadonlyTreeObject
Type: ReadonlyTreeObject
ReadonlyTreeObjectRead-only string-keyed object branch.
TreeValue
Type: TreeValue
TreeValueRecursive mutable tree value.
TreeArray
Type: TreeArray
TreeArrayMutable array branch.
TreeObject
Type: TreeObject
TreeObjectMutable string-keyed object branch.
MutableTree<T>
Type: MutableTree<T>
MutableTree<T>Recursively mutable result corresponding to the inferred input type.
TreeConstraint<T>
Type: TreeConstraint<T>
TreeConstraint<T>Compile-time supported-tree constraint for generic integrations.
InputOpts
Type: InputOpts
InputOptsCleanup, parent filtering, and reporting fields.
SelectorOpts<Value>
Type: SelectorOpts<Value>
SelectorOpts<Value>Required key-only, value-only, or combined selector union.
Opts<Value>
Type: Opts<Value>
Opts<Value>Complete options and selector type.
Only
Type: Only
OnlyAll accepted parent-container aliases.
CompletionStats
Type: CompletionStats
CompletionStatsFrozen completion-report shape.
Defaults
Type: Defaults
DefaultsRead-only exported-defaults shape.
Obj
Type: Obj
ObjDeprecated alias for TreeObject; use the recursive tree types in new code.
import type {
  CompletionStats,
  MutableTree,
  Only,
  Opts,
  ReadonlyTreeValue,
  TreeValue,
} from "object-delete-key";

The declaration rejects guaranteed-invalid trees such as functions, dates, bigint, symbols, and invalid nested unions. Runtime validation additionally enforces the graph, descriptor, and prototype rules described above.

API — version

You can import version:

Permalink to changelogChangelog

Open Changelog
↑ back to top
prev next

Copyright

All rights reserved © Roy Revelt 2026
All our open source packages are under MIT licenceopens in a new tab

Activities

🐛 See a bug? Raise an issueopens in a new tab
💘 Check out the Indiewebopens in a new tab and Libera manifestoopens in a new tab