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