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.