Skip to content

Class: ObjectPath ​

Read, write and test the nested properties of an object by a path: the keys separated by dots, the array indexes as keys or in brackets ('user.addresses[0].city' is 'user.addresses.0.city'). Only the bracketed word characters are recognized: a["b"] and the keys holding a dot cannot be addressed. Its methods are static. set, its only writing method, refuses the paths through __proto__, constructor or prototype, which would modify the prototypes of the objects.

Example ​

typescript
import {ObjectPath} from 'lakutata/utils'

const config: Record<string, any> = {db: {hosts: [{name: 'primary', port: 5432}]}}
console.log(ObjectPath.get<number>(config, 'db.hosts[0].port'), ObjectPath.has(config, 'db.user'))
//5432 false
ObjectPath.set(config, 'db.user.name', 'admin')
console.log(config.db.user)
//{name: 'admin'}

Constructors ​

Constructor ​

new ObjectPath(): ObjectPath

Returns ​

ObjectPath

Methods ​

get() ​

static get<T>(obj, path): T | undefined

Get the value at a path.

Type Parameters ​

T ​

T

Parameters ​

obj ​

Record<string, any>

The object to read.

path ​

string

The path of the value ('a.b[0].c').

Returns ​

T | undefined

The value, or undefined when a key along the path is missing or its value is null or undefined. The value is returned as is, not checked against T.


has() ​

static has(obj, path): boolean

Tell whether a path exists: each of its keys is in the value before it (as an own or inherited property, the in operator), even when the final value is undefined.

Parameters ​

obj ​

Record<string, any>

The object to test.

path ​

string

The path to test ('a.b[0].c').

Returns ​

boolean

true when the whole path exists, false when a key is missing or a value along it is null or undefined.

Throws ​

When a value along the path is a primitive (a string, a number) which is not the last one.


set() ​

static set(obj, path, value): void

Set the value at a path, modifying the object: the missing intermediate keys are created as plain objects (also for numeric keys: 'list[0]' creates {0: ...}, not an array), and an intermediate primitive value is replaced by an object.

Parameters ​

obj ​

Record<string, any>

The object to modify.

path ​

string

The path of the value ('a.b[0].c'). A key __proto__, constructor or prototype anywhere in it is refused, so that a path coming from user input cannot modify the prototype of every object.

value ​

any

The value to set. undefined is ignored: the object is left unchanged (the existing value is kept).

Returns ​

void

Throws ​

When an intermediate value is null, or when the path has a key __proto__, constructor or prototype (the object is left unchanged).

Released under the MIT License.