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 argument | Type | Required | Description |
|---|---|---|---|
inputType: Supported tree value | |||
input | Supported tree value | yes | Value to clone, search, delete from, and optionally clean. |
optsType: Opts selector object | |||
opts | Opts selector object | yes | Selector 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 | |||
| Object | Match the property name | Match the value | Both must match |
| Array | |||
| Array | Match the element value; this is the legacy meaning | No direct array match | No 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
| Key | Type | Required | Default | Description |
|---|---|---|---|---|
keyType: String Default: absent | ||||
key | String | unless val is present | absent | Object-key pattern or legacy array-element pattern. |
valType: Supported tree value Default: absent | ||||
val | Supported tree value | unless key is a string | absent | Object-value pattern. An explicit undefined counts as present. |
cleanupType: Boolean Default: true | ||||
cleanup | Boolean | no | true | Prune affected containers that become strictly empty. |
onlyType: OnlyDefault: "any" | ||||
only | Only | no | "any" | Restrict direct matches to array or object parents. |
reportCompletionFuncType: Function or nullDefault: null | ||||
reportCompletionFunc | Function or null | no | null | Receive frozen completion statistics after a successful call. |
reportProgressFuncType: Function or nullDefault: null | ||||
reportProgressFunc | Function or null | no | null | Receive finite, monotonic progress values during the transformation. |
reportProgressFuncFromType: Finite number Default: 0 | ||||
reportProgressFuncFrom | Finite number | no | 0 | Set the first value in a caller-composable progress range. |
reportProgressFuncToType: Finite number Default: 100 | ||||
reportProgressFuncTo | Finite number | no | 100 | Set 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, andundefined; - ordinary native arrays, including holes and explicit
undefinedelements; 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:
| Key | Description |
|---|---|
directDeletions | |
directDeletions | Object properties and array elements removed by the selector. |
cleanupPrunedContainers | |
cleanupPrunedContainers | Affected non-root containers removed because cleanup found them empty. |
maxDepth | |
maxDepth | Deepest validated entry, with the root value at depth 0. |
totalEntries | |
totalEntries | Validated object properties and array slots, including holes. |
visitedEntries | |
visitedEntries | Object properties and array slots visited during transformation. |
timeTakenInMilliseconds | |
timeTakenInMilliseconds | Best-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:
| Type | Description |
|---|---|
TreePrimitiveType: TreePrimitive | |
TreePrimitive | Supported primitive leaves. |
ReadonlyTreeValueType: ReadonlyTreeValue | |
ReadonlyTreeValue | Recursive read-only input or selector value. |
ReadonlyTreeArrayType: ReadonlyTreeArray | |
ReadonlyTreeArray | Read-only array branch. |
ReadonlyTreeObjectType: ReadonlyTreeObject | |
ReadonlyTreeObject | Read-only string-keyed object branch. |
TreeValueType: TreeValue | |
TreeValue | Recursive mutable tree value. |
TreeArrayType: TreeArray | |
TreeArray | Mutable array branch. |
TreeObjectType: TreeObject | |
TreeObject | Mutable 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. |
InputOptsType: InputOpts | |
InputOpts | Cleanup, 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. |
OnlyType: Only | |
Only | All accepted parent-container aliases. |
CompletionStatsType: CompletionStats | |
CompletionStats | Frozen completion-report shape. |
DefaultsType: Defaults | |
Defaults | Read-only exported-defaults shape. |
ObjType: Obj | |
Obj | Deprecated 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: