Skip to content

lowerize

将对象的所有键名转换为小写。

基础用法

typescript
import { lowerize } from 'radash'

const obj = { Name: 'Alice', AGE: 25, City: 'Beijing' }
const lowerized = lowerize(obj)
console.log(lowerized) // { name: 'Alice', age: 25, city: 'Beijing' }

语法

typescript
function lowerize<T extends Record<string, any>>(obj: T): Record<string, any>

参数

  • obj (T): 要转换键名的对象

返回值

返回一个新对象,所有键名都转换为小写。

示例

基本键名转换

typescript
import { lowerize } from 'radash'

const obj = { Name: 'Alice', AGE: 25, City: 'Beijing' }
const lowerized = lowerize(obj)
console.log(lowerized) // { name: 'Alice', age: 25, city: 'Beijing' }

处理混合大小写

typescript
import { lowerize } from 'radash'

const obj = {
  UserName: 'Alice',
  EMAIL_ADDRESS: 'alice@example.com',
  phoneNumber: '123-456-7890',
  'FIRST_NAME': 'Alice',
  'lastName': 'Smith'
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   username: 'Alice',
//   email_address: 'alice@example.com',
//   phonenumber: '123-456-7890',
//   first_name: 'Alice',
//   lastname: 'Smith'
// }

处理特殊字符

typescript
import { lowerize } from 'radash'

const obj = {
  'User-Name': 'Alice',
  'EMAIL@DOMAIN': 'alice@example.com',
  'Phone_Number': '123-456-7890',
  'First.Name': 'Alice',
  'Last Name': 'Smith'
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   'user-name': 'Alice',
//   'email@domain': 'alice@example.com',
//   'phone_number': '123-456-7890',
//   'first.name': 'Alice',
//   'last name': 'Smith'
// }

处理数字和符号

typescript
import { lowerize } from 'radash'

const obj = {
  'User123': 'Alice',
  'API_V1': 'v1',
  'Test@123': 'test',
  'Hello-World': 'hello',
  'User_Name_123': 'user'
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   'user123': 'Alice',
//   'api_v1': 'v1',
//   'test@123': 'test',
//   'hello-world': 'hello',
//   'user_name_123': 'user'
// }

处理空值和undefined

typescript
import { lowerize } from 'radash'

const obj = {
  Name: 'Alice',
  Email: null,
  Phone: undefined,
  Address: ''
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   name: 'Alice',
//   email: null,
//   phone: undefined,
//   address: ''
// }

处理嵌套对象

typescript
import { lowerize } from 'radash'

const obj = {
  User: {
    Profile: {
      Name: 'Alice',
      AGE: 25
    },
    Settings: {
      Theme: 'dark',
      Language: 'en'
    }
  }
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   user: {
//     profile: {
//       name: 'Alice',
//       age: 25
//     },
//     settings: {
//       theme: 'dark',
//       language: 'en'
//     }
//   }
// }

处理数组值

typescript
import { lowerize } from 'radash'

const obj = {
  UserNames: ['Alice', 'Bob', 'Charlie'],
  EmailAddresses: ['alice@example.com', 'bob@example.com'],
  PhoneNumbers: ['123-456-7890', '098-765-4321']
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   usernames: ['Alice', 'Bob', 'Charlie'],
//   emailaddresses: ['alice@example.com', 'bob@example.com'],
//   phonenumbers: ['123-456-7890', '098-765-4321']
// }

处理函数值

typescript
import { lowerize } from 'radash'

const obj = {
  UserHandler: () => 'hello',
  EmailValidator: function() { return true },
  PhoneProcessor: (x: number) => x * 2
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   userhandler: [Function: UserHandler],
//   emailvalidator: [Function: EmailValidator],
//   phoneprocessor: [Function: PhoneProcessor]
// }

处理日期值

typescript
import { lowerize } from 'radash'

const obj = {
  CreatedAt: new Date('2023-01-01'),
  UpdatedAt: new Date('2023-12-31'),
  Birthday: new Date('1998-05-15')
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   createdat: 2023-01-01T00:00:00.000Z,
//   updatedat: 2023-12-31T00:00:00.000Z,
//   birthday: 1998-05-15T00:00:00.000Z
// }

处理布尔值

typescript
import { lowerize } from 'radash'

const obj = {
  IsActive: true,
  IsVerified: false,
  IsPremium: true,
  IsBlocked: false
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   isactive: true,
//   isverified: false,
//   ispremium: true,
//   isblocked: false
// }

处理数字值

typescript
import { lowerize } from 'radash'

const obj = {
  UserID: 1,
  UserScore: 95.5,
  UserRating: 4.8,
  UserCount: 0,
  UserPrice: -10.99
}

const lowerized = lowerize(obj)
console.log(lowerized)
// {
//   userid: 1,
//   userscore: 95.5,
//   userrating: 4.8,
//   usercount: 0,
//   userprice: -10.99
// }

处理API响应数据

typescript
import { lowerize } from 'radash'

const apiResponse = {
  Status: 200,
  Data: { ID: 1, Name: 'Alice' },
  Meta: { Timestamp: new Date(), RequestID: 'req_123456' }
}

const lowerized = lowerize(apiResponse)
console.log(lowerized)
// {
//   status: 200,
//   data: { id: 1, name: 'Alice' },
//   meta: { timestamp: 2023-12-31T12:00:00.000Z, requestid: 'req_123456' }
// }

处理表单数据

typescript
import { lowerize } from 'radash'

const formData = {
  Personal: {
    FirstName: 'Alice',
    LastName: 'Smith',
    EmailAddress: 'alice@example.com'
  },
  Address: {
    StreetAddress: '123 Main St',
    CityName: 'Beijing',
    CountryCode: 'CN'
  },
  Preferences: {
    NewsletterSubscription: true,
    EmailNotifications: true,
    SMSNotifications: false
  }
}

const lowerized = lowerize(formData)
console.log(lowerized)
// {
//   personal: {
//     firstname: 'Alice',
//     lastname: 'Smith',
//     emailaddress: 'alice@example.com'
//   },
//   address: {
//     streetaddress: '123 Main St',
//     cityname: 'Beijing',
//     countrycode: 'CN'
//   },
//   preferences: {
//     newslettersubscription: true,
//     emailnotifications: true,
//     smsnotifications: false
//   }
// }

处理配置对象

typescript
import { lowerize } from 'radash'

const config = {
  ServerConfig: {
    HostName: 'localhost',
    PortNumber: 3000,
    EnableSSL: true
  },
  DatabaseConfig: {
    ConnectionURL: 'postgresql://localhost:5432/mydb',
    PoolSettings: { MinConnections: 1, MaxConnections: 10 }
  },
  APIConfig: {
    VersionNumber: 'v1',
    RateLimitSettings: { WindowMilliseconds: 900000, MaxRequests: 100 }
  }
}

const lowerized = lowerize(config)
console.log(lowerized)
// {
//   serverconfig: {
//     hostname: 'localhost',
//     portnumber: 3000,
//     enablessl: true
//   },
//   databaseconfig: {
//     connectionurl: 'postgresql://localhost:5432/mydb',
//     poolsettings: { minconnections: 1, maxconnections: 10 }
//   },
//   apiconfig: {
//     versionnumber: 'v1',
//     ratelimitsettings: { windowmilliseconds: 900000, maxrequests: 100 }
//   }
// }

处理错误对象

typescript
import { lowerize } from 'radash'

const errorObject = {
  ErrorName: 'ValidationError',
  ErrorMessage: 'Invalid input',
  ErrorDetails: {
    FieldName: 'email',
    FieldValue: 'invalid-email',
    ValidationConstraints: { Format: 'Must be a valid email' }
  }
}

const lowerized = lowerize(errorObject)
console.log(lowerized)
// {
//   errorname: 'ValidationError',
//   errormessage: 'Invalid input',
//   errordetails: {
//     fieldname: 'email',
//     fieldvalue: 'invalid-email',
//     validationconstraints: { format: 'Must be a valid email' }
//   }
// }

处理日志数据

typescript
import { lowerize } from 'radash'

const logEntry = {
  LogTimestamp: new Date(),
  LogLevel: 'ERROR',
  LogMessage: 'Database connection failed',
  LogContext: { UserID: 123, RequestID: 'req_456' },
  ErrorInfo: { ErrorCode: 'ECONNREFUSED', ErrorMessage: 'Connection refused' }
}

const lowerized = lowerize(logEntry)
console.log(lowerized)
// {
//   logtimestamp: 2023-12-31T12:00:00.000Z,
//   loglevel: 'ERROR',
//   logmessage: 'Database connection failed',
//   logcontext: { userid: 123, requestid: 'req_456' },
//   errorinfo: { errorcode: 'ECONNREFUSED', errormessage: 'Connection refused' }
// }

处理数据库查询结果

typescript
import { lowerize } from 'radash'

const dbResult = {
  RecordID: 1,
  ProductName: 'Product A',
  CategoryInfo: {
    CategoryID: 5,
    CategoryName: 'Electronics'
  },
  ProductVariants: [
    { VariantID: 101, ColorName: 'Red', PriceValue: 99.99 },
    { VariantID: 102, ColorName: 'Blue', PriceValue: 89.99 }
  ]
}

const lowerized = lowerize(dbResult)
console.log(lowerized)
// {
//   recordid: 1,
//   productname: 'Product A',
//   categoryinfo: {
//     categoryid: 5,
//     categoryname: 'Electronics'
//   },
//   productvariants: [
//     { variantid: 101, colorname: 'Red', pricevalue: 99.99 },
//     { variantid: 102, colorname: 'Blue', pricevalue: 89.99 }
//   ]
// }

处理空对象和边界情况

typescript
import { lowerize } from 'radash'

// 空对象
console.log(lowerize({})) // {}

// 只有一个键值对
console.log(lowerize({ Key: 'value' })) // { key: 'value' }

// 包含空值
console.log(lowerize({ Name: 'Alice', Email: null, Phone: undefined }))
// { name: 'Alice', email: null, phone: undefined }

// 所有键都是小写
console.log(lowerize({ name: 'Alice', age: 25 }))
// { name: 'Alice', age: 25 }

处理复杂嵌套对象

typescript
import { lowerize } from 'radash'

const complexObj = {
  UserProfile: {
    PersonalInfo: {
      FullName: 'Alice Smith',
      AgeValue: 25,
      ContactDetails: {
        EmailAddress: 'alice@example.com',
        PhoneNumber: '123-456-7890'
      }
    },
    UserSettings: {
      ThemePreference: 'dark',
      NotificationSettings: {
        EmailNotifications: true,
        PushNotifications: false
      }
    }
  },
  SystemInfo: {
    VersionNumber: '1.0.0',
    EnvironmentType: 'production',
    FeatureFlags: ['feature1', 'feature2']
  }
}

const lowerized = lowerize(complexObj)
console.log(lowerized)
// {
//   userprofile: {
//     personalinfo: {
//       fullname: 'Alice Smith',
//       agevalue: 25,
//       contactdetails: {
//         emailaddress: 'alice@example.com',
//         phonenumber: '123-456-7890'
//       }
//     },
//     usersettings: {
//       themepreference: 'dark',
//       notificationsettings: {
//         emailnotifications: true,
//         pushnotifications: false
//       }
//     }
//   },
//   systeminfo: {
//     versionnumber: '1.0.0',
//     environmenttype: 'production',
//     featureflags: ['feature1', 'feature2']
//   }
// }

注意事项

  1. 键名转换: 所有键名都会被转换为小写
  2. 嵌套对象: 递归处理嵌套对象的所有键名
  3. 数组值: 数组中的对象键名也会被转换
  4. 不可变性: 返回新对象,不修改原对象
  5. 特殊字符: 保留键名中的特殊字符,只转换字母部分

与其他方法的区别

  • upperize(): 将键名转换为大写
  • lowerize(): 将键名转换为小写
  • camel(): 转换为驼峰命名法
  • pascal(): 转换为帕斯卡命名法

实际应用场景

  1. API标准化: 统一API响应的键名格式
  2. 数据库映射: 处理数据库字段名的大小写
  3. 配置处理: 标准化配置文件中的键名
  4. 数据转换: 在不同系统间转换数据格式
  5. 表单处理: 统一表单字段名的大小写

Released under the MIT License.