Open In App

Underscore _.toPath() Function

Last Updated : 07 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </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:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </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>


Output:

{"a":[{"b":5}]}
 a.0.b

Reference: https://underscorejs.org/#toPath



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads