Skip to main content

toPath()

toPath(value): string[]

Converts value to a property path array.

๐Ÿ’Ž Why is this a Hidden Gem?

Parse dot-notation strings like 'a.b[0].c' into clean path arrays.

DEPRECATED

Use string split or manual parsing instead.


Parametersโ€‹

value: string | null | undefinedโ€‹

The value to convert.


Returns: string[]โ€‹

The new property path array.


Sinceโ€‹

2.0.0


Also known asโ€‹

toPath (Lodash, es-toolkit) ยท โŒ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)


Exampleโ€‹

// โŒ Deprecated approach
toPath('a.b.c'); // => ['a', 'b', 'c']
toPath('a[0].b.c'); // => ['a', '0', 'b', 'c']

// โœ… Recommended approach
'a.b.c'.split('.'); // => ['a', 'b', 'c']
// For complex paths with brackets:
'a[0].b.c'.replace(/\[(\d+)\]/g, '.$1').split('.').filter(Boolean);
// => ['a', '0', 'b', 'c']

How it works?โ€‹

Converts string path to array of keys. Deprecated: Use split or regex directly.

Native Equivalentโ€‹

// โŒ toPath('a.b.c')
// โœ… 'a.b.c'.split('.')

Use Casesโ€‹

Parse property path ๐Ÿ“Œโ€‹

Parse string path into segments.

"a.b.c".split(".");        // => ["a", "b", "c"]
"a[0].b".match(/[^.[\]]+/g); // => ["a", "0", "b"]

Build path accessorโ€‹

Access nested properties by path.

const get = (obj, path) => 
path.split(".").reduce((o, k) => o?.[k], obj);

get(data, "user.address.city");

Handle array notationโ€‹

Support both dot and bracket notation.

const segments = "a[0].b[1].c"
.replace(/\[(\d+)\]/g, ".$1")
.split(".");
// => ["a", "0", "b", "1", "c"]