Skip to content

get

Gets a value from an object using a dot/bracket-notated path or explicit key array.

Two path forms are supported:

  1. String path — dot notation ('a.b.c') and bracket notation ('layers[1].name') are both accepted and mixed freely.

    • Dot segments are always string keys: 'a.1' → key '1' (string).
    • Bracket segments are always number keys: 'a[1]' → key 1 (number).
    • String literal paths give full compile-time type inference on the return type.
    • Dynamic (non-literal) strings return unknown.
  2. Key array (PropertyKey[]) — explicit array of string | number | symbol keys, no parsing performed. Enables symbol-keyed traversal and compile-time type inference: get(obj, ['a', 'b'] as const) infers the return type from the path.

Both forms support all objects (plain objects, arrays, class instances). Symbol keys are only reachable via the key-array form.

Available since v1.9.0

import { get } from '@helpers4/object';
get<D>(obj: null | undefined, path: string | readonly PropertyKey[], defaultValue: D): D
ParameterTypeDescription
objnull | undefinedThe object to read from
pathstring | readonly PropertyKey[]Dot/bracket-notation string literal or explicit PropertyKey[]
defaultValueDReturned when the path is absent or resolves to undefined

D — The value at the path, or defaultValue

Uses a dot-notated path to retrieve a deeply nested value.

get({ a: { b: { c: 42 } } }, 'a.b.c')
// => 42

Returns the default value when the path does not exist.

get({ a: 1 }, 'b.c', 'default')
// => 'default'

Pass an explicit PropertyKey[] to bypass parsing. Supports string, number, and symbol keys.

const id = Symbol('id')
get({ [id]: 'alice' }, [id])
// => 'alice'

View source on GitHub