@nixat/get
v0.1.1
Published
A utility function to safely get nested object properties
Readme
@nixat/get
A utility function to safely get nested object properties.
Installation
# Using npm
npm install @nixat/get
# Using yarn
yarn add @nixat/get
# Using pnpm
pnpm add @nixat/getUsage
import { get } from '@nixat/get';
// Basic usage
const obj = { a: { b: { c: 42 } } };
get(obj, 'a.b.c'); // => 42
// With default value
get(obj, 'a.b.d', 'default'); // => 'default'
// Using array path
get(obj, ['a', 'b', 'c']); // => 42
// Handling null/undefined
get(null, 'a.b.c', 'default'); // => 'default'
get(undefined, 'a.b.c', 'default'); // => 'default'
// Handling arrays
const arr = { users: [{ name: 'John' }, { name: 'Jane' }] };
get(arr, 'users.0.name'); // => 'John'
get(arr, ['users', 1, 'name']); // => 'Jane'API
get(obj, path, defaultValue?)
Safely gets a value from a nested object using a path string or array.
Parameters
obj- The object to querypath- The path to get the property from, can be a dot-notation string or array of keysdefaultValue- The value to return if the path doesn't exist
Returns
The value at the path or the default value.
License
MIT
