JavaScript: Array field uppercase to lowercase

We can use forEach()the method to iterate over each object in the array and convert all fields to lowercase.

First forEach()iterate over each object in the array using the method. Then, use Object.keys()the method to get all the field names in the object and convert them all to lowercase. Finally, reassign the lowercase field names to the object and delete the original uppercase field names. The final output is a new array with all field names converted to lowercase.

Code:

let arr = [
  {
    
     Name: 'John', Age: 25 },
  {
    
     Name: 'Mary', Age: 30 },
  {
    
     Name: 'Peter', Age: 35 }
];

arr.forEach(obj => {
    
    
  Object.keys(obj).forEach(key => {
    
    
    obj[key.toLowerCase()] = obj[key];
    delete obj[key];
  });
});

console.log(arr);

output:

[
  {
    
     name: 'John', age: 25 },
  {
    
     name: 'Mary', age: 30 },
  {
    
     name: 'Peter', age: 35 }
]

Successfully converted uppercase fields in the array to lowercase.

Guess you like

Origin blog.csdn.net/weixin_46098577/article/details/131390475