Underscore.js _.getPath() Method

The _.getPath() method is used to get the value at any depth in a nested object based on the path described by the given keys. Keys may be given as an array or as a dot-separated string. 

Syntax:

_.getPath( Object_name, key_string|array );

Parameters: 

  • Object_name: Object from which the value is to be searched.
  • key_string | array: Given dot-separated string or array to be searched in the given object.

Return Value: This method returns a value searched from the object.

Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed. Underscore.js contrib library can be installed using npm install underscore-contrib –save.



Example 1: Getting the value using a dot-separated string.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var ob = { gfg : {
        GeeksforGeeks :  "Computer Science Portal for Geeks"
    }
};
var val = _.getPath( ob, "gfg.GeeksforGeeks" );
  
console.log(val);

chevron_right


Output:

Computer Science Portal for Geeks

Example 2: Getting value using an array.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var ob = { gfg : {
        GeeksforGeeks :  "Computer Science Portal for Geeks"
    }
};
var val = _.getPath( ob, ['gfg', 'GeeksforGeeks'] );
  
console.log(val);

chevron_right


Output:

Computer Science Portal for Geeks

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.