Open In App

Underscore _.get() Function

Last Updated : 01 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects.

The _.get() function is an inbuilt function in the Underscore.js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place.

Syntax:

_.get(object, path, [defaultValue])

Parameters: This method accepts three parameters as mentioned above and described below:

  • object: This parameter holds the object to query.
  • path: This parameter holds the path of the property to get. The path will be array or string.
  • defaultValue: This parameter holds the value returned for undefined resolved values.
  • Return Value: This method returns the resolved value.

Example 1:

HTML




<!DOCTYPE html>
<html>
<head>
    <script src=
    </script>
</head>
<body>
    <script
        // Given object
        var object = { 'c': [{ 'python': { 'java': 3 } }] };
            
        // Use of _.get method 
        console.log(_.get(object, 'c')); 
    </script>
</body>
</html>


Output:

[{ 'python': { 'java': 3 } }] 

Example 2:

HTML




<!DOCTYPE html>
<html>
<head>
    <script src=
    </script>
</head>
<body>
    <script>        
        // Given object
        var object = { 'c': [{ 'python': { 'java': 3 } }] };
            
        // Use of _.get method 
        console.log(_.get(object, ['c', '0', 'python', 'java'])); 
    </script>
</body>
</html>


Output:

3

Example 3:

HTML




<!DOCTYPE html>
<html>
<head>
    <script src=
    </script>
</head>
<body>
    <script>     
        // Given object
        var object = { 'c': [{ 'python': { 'java': 3 } }] };
            
        // Use of _.get method 
        console.log(_.get(object, 'c.python.java', 'default')); 
    </script>
</body>
</html>


Output:

default

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads