Open In App

Underscore _.toPath() Function

Last Updated : 07 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
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=
"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:

HTML
<!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>

Output:

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

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


Next Article

Similar Reads