CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-get-value

Use property paths like 'a.b.c' to get a nested value from an object, even works when keys have dots in them.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Get Value

Get Value is a robust utility for retrieving nested values from JavaScript objects using property path strings (like 'a.b.c') or arrays. It stands out from other dot-prop libraries by correctly handling keys that contain dots, supporting escaped characters, and offering extensive customization options.

Package Information

  • Package Name: get-value
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install get-value

Core Imports

ESM (ES Modules):

import getValue from "get-value";

CommonJS:

const getValue = require("get-value");

The package provides dual module support with both ESM and CommonJS exports.

Basic Usage

import getValue from "get-value";

const obj = {
  a: {
    b: {
      c: 'nested value'
    }
  }
};

// Basic path access
const value = getValue(obj, 'a.b.c');
console.log(value); // 'nested value'

// With default value
const missing = getValue(obj, 'a.b.d', { default: 'fallback' });
console.log(missing); // 'fallback'

// Array paths
const arrayValue = getValue(obj, ['a', 'b', 'c']);
console.log(arrayValue); // 'nested value'

Architecture

Get Value uses a sophisticated path traversal algorithm that:

  • Safe Navigation: Never throws errors, returns default values for missing paths
  • Dot Handling: Correctly handles object keys that contain dots by trying multiple path combinations
  • Escape Support: Supports backslash escaping for path segments containing special characters
  • Custom Processing: Allows custom split/join functions for advanced path processing
  • Validation: Optional validation function for each key access
  • Type Flexibility: Handles strings, numbers, and arrays as path inputs

Capabilities

Core Function

Main function for retrieving nested values from objects using property paths.

/**
 * Retrieves nested values from objects using dot notation paths or arrays
 * @param target - The object to retrieve values from
 * @param path - Property path (dot notation string, array of segments, or number)
 * @param options - Configuration options or default value for backwards compatibility
 * @returns The retrieved value or default value if not found
 */
function getValue<T>(target: T): T;
function getValue(target: object, path: string | string[], options?: Options): any;
function getValue(target: object, path: string | string[], defaultValue?: any): any;

Usage Examples:

import getValue from "get-value";

// Return entire object when no path provided
const data = { user: { profile: { name: 'John' } } };
getValue(data); // { user: { profile: { name: 'John' } } }

// Basic nested access
getValue(data, 'user.profile.name'); // 'John'

// Array index access
const users = { items: ['Alice', 'Bob', 'Charlie'] };
getValue(users, 'items.1'); // 'Bob'

// Keys with dots
const config = { 'api.endpoint': { url: 'https://api.com' } };
getValue(config, 'api.endpoint.url'); // 'https://api.com'

// Default values with options object
getValue(data, 'user.settings.theme', { default: 'light' }); // 'light'

// Legacy syntax (default as third parameter)
getValue(data, 'missing.path', 'fallback'); // 'fallback'

// Array path notation
getValue(data, ['user', 'profile', 'name']); // 'John'

Configuration Options

Options interface for customizing getValue behavior.

interface Options {
  /** Default value to return when property not found */
  default?: any;
  /** Custom separator for splitting paths (default: '.') */
  separator?: string | RegExp;
  /** Character for rejoining path segments (default: same as separator) */
  joinChar?: string;
  /** Custom function for joining path segments */
  join?: (segs: string[]) => string;
  /** Custom function for splitting paths */
  split?: (path: string) => string[];
  /** Validation function for each resolved key */
  isValid?: <K extends string>(key: K, object: Record<K, any>) => boolean;
}

Advanced Configuration Examples:

import getValue from "get-value";

// Custom separator
const data = { 'a.b': { c: { d: 'value' } } };
getValue(data, 'a.b/c/d', { separator: '/' }); // 'value'

// Regex separator for escaped dots
getValue(data, 'a\\.b.c.d', { separator: /\\?\./ }); // 'value'

// Custom split function
getValue(data, 'a.b|c|d', {
  split: (path) => path.split('|')
}); // 'value'

// Custom join character for keys with different separator
const config = { 'api-key': { settings: 'value' } };
getValue(config, 'api.key.settings', { joinChar: '-' }); // 'value'

// Validation function
getValue(data, 'a.b.c', {
  isValid: (key, obj) => obj.hasOwnProperty(key)
}); // Only access own properties

// Multiple options
getValue(data, 'complex/path', {
  separator: '/',
  default: null,
  isValid: (key, obj) => typeof obj[key] !== 'undefined'
});

Escape Sequences

Get Value supports backslash escaping for path segments containing special characters.

Escape Handling Examples:

import getValue from "get-value";

// Escaped dots in path segments
const obj = { 'file.txt': { content: 'data' } };
getValue(obj, 'file\\.txt.content'); // 'data'

// Multiple escapes
const complex = { 'a.b': { 'c.d': { 'e.f': 'nested' } } };
getValue(complex, 'a\\.b.c\\.d.e\\.f'); // 'nested'

// Mixed escaped and unescaped
getValue(complex, 'a\\.b.c\\.d', { default: 'missing' }); // { 'e.f': 'nested' }

Path Format Support

The function accepts multiple path formats for maximum flexibility.

Path Format Examples:

import getValue from "get-value";

const data = {
  users: [
    { profile: { name: 'Alice' } },
    { profile: { name: 'Bob' } }
  ]
};

// String paths with dot notation
getValue(data, 'users.0.profile.name'); // 'Alice'

// Array paths
getValue(data, ['users', '1', 'profile', 'name']); // 'Bob'

// Numeric paths (converted to string)
getValue(data, 123); // data['123'] if it exists

// Mixed array with different types
getValue(data, ['users', 0, 'profile', 'name']); // 'Alice'

// Numeric keys are converted to strings
const obj = { 123: 'numeric key' };
getValue(obj, 123); // 'numeric key'

Function Support

Get Value works with functions as target objects, accessing their properties.

Function Target Examples:

import getValue from "get-value";

// Functions with properties
function myFunction() {}
myFunction.config = { debug: true };
myFunction.metadata = { version: '1.0' };

getValue(myFunction); // Returns the function itself
getValue(myFunction, 'config'); // { debug: true }
getValue(myFunction, 'config.debug'); // true
getValue(myFunction, 'metadata.version'); // '1.0'

// Nested function properties
function api() {}
api.endpoints = {
  users: { url: '/api/users' },
  posts: { url: '/api/posts' }
};

getValue(api, 'endpoints.users.url'); // '/api/users'

Error Handling

Get Value never throws exceptions and handles edge cases gracefully.

Error Handling Examples:

import getValue from "get-value";

// Null/undefined targets
getValue(null, 'any.path'); // null
getValue(undefined, 'any.path'); // undefined
getValue(null, 'any.path', { default: 'safe' }); // 'safe'

// Invalid paths
getValue({}, null); // {}
getValue({}, undefined); // {}

// Non-object intermediate values
const data = { a: 'string', b: 42 };
getValue(data, 'a.nested.prop'); // undefined
getValue(data, 'a.nested.prop', { default: 'fallback' }); // 'fallback'

// Array access on non-arrays
getValue({ items: 'not-array' }, 'items.0'); // undefined
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/get-value@4.0.x
Publish Source
CLI
Badge
tessl/npm-get-value badge