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"]