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