Underscore.js _.renameKeys() Method
Last Updated :
13 Aug, 2020
The _.renameKeys() method takes an object and a mapping object and returns a new object where the keys of the given object have been renamed as the corresponding value in the keyMap.
Syntax:
_.renameKeys(obj, mapObj);
Parameters:
- obj: Given object to create a new object.
- mapObj: Given map object to create a new object.
Return Value: This method returns a generated 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:
Javascript
var _ = require( 'underscore-contrib' );
var obj = _.renameKeys( { 1 : "Geeks" ,
2 : "Computer_Science_Portal" },
{ 1 : "g" , 2 : "c" });
console.log( "Generated Object: " , obj);
|
Output:
Generated Object: { g: 'Geeks', c: 'Computer_Science_Portal' }
Example 2: If two or more key value pair is coming to be the same in the object, the generated object will have a unique key value pair.
Javascript
var _ = require( 'underscore-contrib' );
var obj = _.renameKeys(
{ 1 : "Geeks" , 2 : "Computer_Science_Portal" ,
3 : "Geeks" }, { 1 : "g" , 2 : "c" , 3 : "g" });
console.log( "Generated Object: " , obj);
|
Output:
Generated Object: { g: 'Geeks', c: 'Computer_Science_Portal' }
Example 3: If the given object is an arr, new object created will be mapped using the index of objects of that array.
Javascript
var _ = require( 'underscore-contrib' );
var obj = _.renameKeys( [ "Computer_Science_Portal" , "Geeks" ],
{ 0 : "a" , 1 : "b" , 3 : "g" });
console.log( "Generated Object: " , obj);
|
Output:
Generated Object: { a: 'Computer_Science_Portal', b: 'Geeks' }
Share your thoughts in the comments
Please Login to comment...