Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.mapValues() method is used to create a new mapped object with the same keys of the given object and the values are generated using the given iteratee function.
Syntax:
_.mapValues( object, iteratee )
Parameters: This method accepts two parameters as mentioned above and described below:
- object: This parameter holds the object to iterate over.
- iteratee: This parameter holds the function that is invoked per iteration on the object. It is an optional value.
Return Value: This method returns the new mapped object.
Example 1:
Javascript
// Requiring the lodash library const _ = require( "lodash" ); Â
var users = { 'Geeksforneveropen' : { Â Â Â Â 'username' : 'gfg_id' , Â Â Â Â 'password' : 'gfg@123' Â Â }, Â Â 'W3school' : { Â Â Â Â 'username' : 'w3school_id' , Â Â Â Â 'password' : 'w@123' Â Â } }; Â
// Using the _.mapValues() method console.log( Â Â _.mapValues(users, function (o) { Â Â Â Â return o.password; Â Â }) ); |
Â
Â
Output:
Â
{Geeksforneveropen: "gfg@123", W3school: "w@123"}
Â
Example 2: Â
Â
Javascript
// Requiring the lodash library const _ = require( "lodash" ); Â
var users = { Â Â 'Geeksforneveropen' : { Â Â Â Â 'username' : 'gfg_id' , Â Â Â Â 'password' : 'gfg@123' Â Â }, Â Â 'W3school' : { Â Â Â Â 'username' : 'w3school_id' , Â Â Â Â 'password' : 'w@123' Â Â } }; Â
// Using the _.mapValues() method console.log(_.mapValues(users, 'password' )); |
Output:
{Geeksforneveropen: "gfg@123", W3school: "w@123"}