Thursday, February 26, 2026
HomeLanguagesJavascriptUnderscore.js _.renameKeys() Method

Underscore.js _.renameKeys() Method

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




// Defining underscore contrib variable
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




// Defining underscore contrib variable
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




// Defining underscore contrib variable
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' }
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS