@pfeiferio/dotpath-utils
v1.0.0
Published
Low-level utilities for working with nested objects and dot-notation paths, including mixed object/array structures and sparse arrays
Downloads
113
Maintainers
Readme
@pfeiferio/dotpath-utils
Utility functions for working with nested objects and dot notation paths.
The package provides low-level helpers to get, set and transform values using dot notation paths. It supports mixed object/array structures and handles sparse arrays correctly.
Requirements
- Node.js >= 18
- ESM-only package
Installation
npm install @pfeiferio/dotpath-utilsor
yarn add @pfeiferio/dotpath-utilsUsage
Importing the Functions
import {
getValueByPath,
setMultipleValuesByPaths,
setValueByPath,
toDotNotation,
toNestedObject
} from '@pfeiferio/dotpath-utils'Functions
getValueByPath
Retrieves a value from an object at a given dot notation path.
Returns undefined if the path does not exist or if the input is not an object.
const obj = {a: {b: {c: 42}}}
getValueByPath(obj, 'a.b.c') // 42setMultipleValuesByPaths
Sets multiple values in an object or array at given dot notation paths.
const pathsAndValues = {
'0.1.0.0': 5,
'0.1.0.3': 6
}
setMultipleValuesByPaths([], pathsAndValues)
// → [ [ <empty>, [ [5, <empty>, <empty>, 6] ] ] ]setValueByPath
Sets a value in an object at a given dot notation path.
const obj = {}
setValueByPath(obj, 'a.b.c', 42)
// → { a: { b: { c: 42 } } }toDotNotation
Converts a nested object or array to dot notation.
toDotNotation({a: {b: {c: 42}}})
// → { 'a.b.c': 42 }toNestedObject
Converts a dot notation path and value into a nested object or array.
toNestedObject('a.b.c', 42)
// → { a: { b: { c: 42 } } }Tests
Tests are implemented using Node.js built-in test runner.
npm test