The Underscore.js _.toPath() function is used to convert the given value to a property path array.
Syntax:
_.toPath('key')
Parameters: This method accepts a single parameter as mentioned above and described below.
key: The key value that need to convert to path array.
Return Value: The new property path array.
Below example illustrates the _.getPath() function is Underscore.js.
Example 1:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://cdn.jsdelivr.net/npm/underscore@latest/underscore-umd-min.js">
</script>
</head>
<body>
<script type="text/javascript">
// Use of _.toPath() method
let gfg = _.toPath(['geeks', 'for', 'geeks']);
// Printing the output
console.log(gfg);
</script>
</body>
</html>
Output:
["geeks","for","geeks"]
Example 2:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://cdn.jsdelivr.net/npm/underscore@latest/underscore-umd-min.js">
</script>
</head>
<body>
<script type="text/javascript">
var originalToPath = _.toPath;
_.mixin({
toPath: function (path) {
return _.isString(path) ?
path.split('.') : originalToPath(path);
}
});
console.log({
a: [{
b: 5
}]
}, 'a.0.b');
</script>
</body>
</html>