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 }