es-toolkit/docs/reference/object/get.md
PiQuark6046 a186e5d4bd
feat(get): Add get (#232)
* feat: get

* chore: add benchmark of get

* test: get

* feat: get

* docs: get

* Update src/object/get.ts

---------

Co-authored-by: Sojin Park <raon0211@toss.im>
Co-authored-by: Sojin Park <raon0211@gmail.com>
2024-07-18 21:17:15 +09:00

814 B

get

Returns the value of an object based on the parts for the given object.

Signature

function get<O, T>(obj: O, path: string | string[], defaultValue?: T): O[keyof O] | T | undefined;

Parameters

  • obj (O): The object to browse.
  • path (string or string[]): The part about the object to be found.
  • defaultValue (T): If the value of the object based on the part doesn't exist, this is the value to return instead.

Returns

(O[keyof O], T or undefined): undefined, the value returned instead, or some specific value for the given object.

Examples

const obj = {
  a: {
    b: 4
  }
}
console.log(obj, 'a.b') // 4
console.log(obj, ['a', 'b']) // 4
console.log(obj, ['a', 'c']) // undefined
console.log(obj, ['a', 'c'], null) // null