Monday, November 18, 2024
Google search engine
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

Most Popular

Recent Comments