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:
Input: {RollNo : 1, Mark : 78}
Output: {rollno : 1, mark : 78}
Explanation: here, we have converted upper case to lower case keys values.
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 object. And use String.toLowerCase() method to lower case keys and Array.reduce() method to make an object with lower-case strings.
Example 1:
HTML
< script > // 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); </ script > |
Output:
{ rollno : 1, mark : 78}
Approach 2:
The simplest approach is to convert Object to array and make keys to lower-case 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:
HTML
< script > // 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) </ script > |
Output:
{ empid : 101, batch : 56 }