Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to create a new object from the specified object, where all...

How to create a new object from the specified object, where all the keys are in lowercase in JavaScript?

In this article, we will learn how to make a new object from the specified object where all the keys are in lowercase using JavaScript.

Example: Here, we have converted the upper case to lower case key values.

Input: {RollNo : 1, Mark : 78}

Output: {rollno : 1, mark : 78}

Approach 1: A simple approach is to Extract keys from Object and LowerCase to all keys and make Object with them. For this purpose we use Object.keys( ) to extract keys from the object. And use String.toLowerCase() method to lower case keys and Array.reduce() method to make an object with lower-case strings. 

Example: This example shows the above-explained approach.

Javascript




// Test Object
const Student = { RollNo : 1, Mark: 78 };
  
// Function to lowercase keys 
function Conv( obj , key )
{
  obj[key.toLowerCase()] = Student[key];
  return Student;
}
  
// Function to  create object from lowercase keys 
function ObjKeys( obj) {
  let arr1 = Object.keys(obj);
  let ans = {};
  for(let i of arr1)
  {
  Conv(ans,i);
  
  }
  return ans;
}
  
a = ObjKeys(Student);
console.log(a);


Output:

{ rollno : 1, mark : 78}

Approach 2: The simplest approach is to convert the Object to an array and make keys lowercase and make objects from a new array. For this purpose, we use Object.entries() to make an array from Object. And we use Array.map() to apply String.toLowerCase() method to all keys. To convert a new array to an Object we use Object.fromEntries().

Example: This example shows the above-explained approach.

Javascript




// Test Object
const employ = { EmpId: 101, Batch: 56 };
  
// Converting Object to array 
let k = Object.entries(employ);
  
//  Apply toLowerCase function to all keys 
let l = k.map(function(t){
  t[0] = t[0].toLowerCase()
  return t;
  }
);
  
// Converting back array to Object
const a  = Object.fromEntries(l)
console.log(a)


Output:

{ empid : 101, batch : 56 } 

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!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments