deeprecursivevalueaccessor
v1.0.4
Published
A module to access deeply nested values in an object
Downloads
2
Readme
Deep Property Accessor
A TypeScript utility for safely and efficiently accessing deeply nested properties in objects and arrays.
Features
- Safely traverse deeply nested objects and arrays
- Handle various key types including strings, numbers, and symbols
- Optimized for performance, even with extremely deep structures
- Provides both a direct access method and a safe wrapper
- Custom error class for detailed error information
- Fully typed with TypeScript for improved developer experience
Potential use cases
- Safely accessing nested properties in complex object structures.
- Working with configuration objects or API responses with deep nesting.
- Implementing flexible data access patterns in JavaScript/TypeScript applications.
Installation
npm install deep-property-accessor
Usage
Basic Usage
import { returnDeepProperty } from 'deep-property-accessor';
const obj = {
a: {
b: [
{ c: 1 },
{ c: 2 }
]
}
};
const result = returnDeepProperty(obj, ['a', 'b', 1, 'c']);
console.log(result); // Output: 2
Safe Usage
import { safeReturnDeepProperty } from 'deep-property-accessor';
const obj = {
a: {
b: [
{ c: 1 },
{ c: 2 }
]
}
};
const result = safeReturnDeepProperty(obj, ['a', 'x', 'y']);
console.log(result); // Output: { value: undefined, error: "Property 'x' does not exist" }
Error Handling
import { returnDeepProperty, PropertyAccessError } from 'deep-property-accessor';
try {
const result = returnDeepProperty(obj, ['a', 'b', 'c']);
} catch (error) {
if (error instanceof PropertyAccessError) {
console.log(`Error at path: ${error.path.join('.')}`);
console.log(`Problem segment: ${String(error.segment)}`);
console.log(`Error message: ${error.message}`);
}
}