Underscore.js _.accessor() Method

The _.accessor() method returns a function that will attempt to look up a given field in the given object.

Syntax:

funct = _.accessor( field_name );

Parameters: 

  • field_name: This method takes the field to be searched in the given object.

Return Value: This method returns a function that will attempt to look up a given field in the given 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var ob = { gfg : "GeeksforGeeks" }
var gfgg = _.accessor('gfg');
  
console.log(gfgg(ob));

chevron_right


Output:

GeeksforGeeks

Example 2: If this function does not find any field then it will return undefined.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var ob = { gfg : "GeeksforGeeks" }
var gfgg = _.accessor('geeks');
  
console.log(gfgg(ob));

chevron_right


Output:

undefined

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.