upperize
Convert all key names of an object to uppercase, recursively processing nested objects.
Basic Usage
typescript
import { upperize } from 'radash'
const obj = { name: 'Alice', age: 25, city: 'Beijing' }
const upperized = upperize(obj)
console.log(upperized) // { NAME: 'Alice', AGE: 25, CITY: 'Beijing' }
Syntax
typescript
function upperize<T extends Record<string, any>>(obj: T): Record<string, any>
Parameters
obj
(T): The object whose key names you want to convert
Return Value
Returns a new object with key names converted to uppercase, recursively processing nested objects.
Examples
Basic Key Name Conversion
typescript
import { upperize } from 'radash'
const obj = { name: 'Alice', age: 25, city: 'Beijing' }
const upperized = upperize(obj)
console.log(upperized) // { NAME: 'Alice', AGE: 25, CITY: 'Beijing' }
Processing Nested Objects
typescript
import { upperize } from 'radash'
const obj = {
user: {
name: 'Alice',
profile: {
email: 'alice@example.com',
settings: {
theme: 'dark',
language: 'en'
}
}
},
settings: {
theme: 'light',
notifications: true
}
}
const upperized = upperize(obj)
console.log(upperized)
// {
// USER: {
// NAME: 'Alice',
// PROFILE: {
// EMAIL: 'alice@example.com',
// SETTINGS: {
// THEME: 'dark',
// LANGUAGE: 'en'
// }
// }
// },
// SETTINGS: {
// THEME: 'light',
// NOTIFICATIONS: true
// }
// }
Processing Array Values
typescript
import { upperize } from 'radash'
const obj = {
users: [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
],
settings: {
colors: ['red', 'blue', 'green'],
numbers: [1, 2, 3, 4, 5]
}
}
const upperized = upperize(obj)
console.log(upperized)
// {
// USERS: [
// { NAME: 'Alice', AGE: 25 },
// { NAME: 'Bob', AGE: 30 }
// ],
// SETTINGS: {
// COLORS: ['red', 'blue', 'green'],
// NUMBERS: [1, 2, 3, 4, 5]
// }
// }
Processing Function Values
typescript
import { upperize } from 'radash'
const obj = {
handlers: {
userHandler: () => 'hello',
emailValidator: function() { return true },
dataProcessor: (x: number) => x * 2
},
callbacks: {
onSuccess: () => console.log('success'),
onError: (err: Error) => console.error(err)
}
}
const upperized = upperize(obj)
console.log(upperized)
// {
// HANDLERS: {
// USERHANDLER: [Function: userHandler],
// EMAILVALIDATOR: [Function: emailValidator],
// DATAPROCESSOR: [Function: dataProcessor]
// },
// CALLBACKS: {
// ONSUCCESS: [Function: onSuccess],
// ONERROR: [Function: onError]
// }
// }
Processing Date Values
typescript
import { upperize } from 'radash'
const obj = {
timestamps: {
createdAt: new Date('2023-01-01'),
updatedAt: new Date('2023-12-31'),
deletedAt: null
},
events: {
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31')
}
}
const upperized = upperize(obj)
console.log(upperized)
// {
// TIMESTAMPS: {
// CREATEDAT: 2023-01-01T00:00:00.000Z,
// UPDATEDAT: 2023-12-31T00:00:00.000Z,
// DELETEDAT: null
// },
// EVENTS: {
// STARTDATE: 2024-01-01T00:00:00.000Z,
// ENDDATE: 2024-12-31T00:00:00.000Z
// }
// }
Processing Boolean Values
typescript
import { upperize } from 'radash'
const obj = {
flags: {
isActive: true,
isVerified: false,
isPremium: true,
isBlocked: false
},
settings: {
enableNotifications: true,
enableDebug: false,
enableLogging: true
}
}
const upperized = upperize(obj)
console.log(upperized)
// {
// FLAGS: {
// ISACTIVE: true,
// ISVERIFIED: false,
// ISPREMIUM: true,
// ISBLOCKED: false
// },
// SETTINGS: {
// ENABLENOTIFICATIONS: true,
// ENABLEDEBUG: false,
// ENABLELOGGING: true
// }
// }
Processing Number Values
typescript
import { upperize } from 'radash'
const obj = {
scores: {
mathScore: 95,
englishScore: 88,
scienceScore: 92
},
prices: {
basePrice: 99.99,
discountPrice: 79.99,
taxAmount: 8.99
}
}
const upperized = upperize(obj)
console.log(upperized)
// {
// SCORES: {
// MATHSCORE: 95,
// ENGLISHSCORE: 88,
// SCIENCESCORE: 92
// },
// PRICES: {
// BASEPRICE: 99.99,
// DISCOUNTPRICE: 79.99,
// TAXAMOUNT: 8.99
// }
// }
Processing API Response Data
typescript
import { upperize } from 'radash'
const apiResponse = {
responseData: {
userId: 1,
userName: 'Alice',
userEmail: 'alice@example.com',
userProfile: {
firstName: 'Alice',
lastName: 'Smith',
age: 25
}
},
responseMeta: {
timestamp: new Date(),
requestId: 'req_123456',
version: 'v1.0.0'
}
}
const upperized = upperize(apiResponse)
console.log(upperized)
// {
// RESPONSEDATA: {
// USERID: 1,
// USERNAME: 'Alice',
// USEREMAIL: 'alice@example.com',
// USERPROFILE: {
// FIRSTNAME: 'Alice',
// LASTNAME: 'Smith',
// AGE: 25
// }
// },
// RESPONSEMETA: {
// TIMESTAMP: 2023-12-31T12:00:00.000Z,
// REQUESTID: 'req_123456',
// VERSION: 'v1.0.0'
// }
// }
Processing Form Data
typescript
import { upperize } from 'radash'
const formData = {
personalInfo: {
firstName: 'Alice',
lastName: 'Smith',
emailAddress: 'alice@example.com',
phoneNumber: '123-456-7890'
},
addressInfo: {
streetAddress: '123 Main St',
cityName: 'Beijing',
countryCode: 'CN',
zipCode: '10001'
}
}
const upperized = upperize(formData)
console.log(upperized)
// {
// PERSONALINFO: {
// FIRSTNAME: 'Alice',
// LASTNAME: 'Smith',
// EMAILADDRESS: 'alice@example.com',
// PHONENUMBER: '123-456-7890'
// },
// ADDRESSINFO: {
// STREETADDRESS: '123 Main St',
// CITYNAME: 'Beijing',
// COUNTRYCODE: 'CN',
// ZIPCODE: '10001'
// }
// }
Processing Configuration Objects
typescript
import { upperize } from 'radash'
const config = {
serverConfig: {
hostName: 'localhost',
portNumber: 3000,
enableSSL: true,
timeoutMs: 5000
},
databaseConfig: {
connectionURL: 'postgresql://localhost:5432/mydb',
poolSettings: {
minConnections: 1,
maxConnections: 10,
idleTimeout: 30000
}
},
apiConfig: {
versionNumber: 'v1',
rateLimitSettings: {
windowMs: 900000,
maxRequests: 100
}
}
}
const upperized = upperize(config)
console.log(upperized)
// {
// SERVERCONFIG: {
// HOSTNAME: 'localhost',
// PORTNUMBER: 3000,
// ENABLESSL: true,
// TIMEOUTMS: 5000
// },
// DATABASECONFIG: {
// CONNECTIONURL: 'postgresql://localhost:5432/mydb',
// POOLSETTINGS: {
// MINCONNECTIONS: 1,
// MAXCONNECTIONS: 10,
// IDLETIMEOUT: 30000
// }
// },
// APICONFIG: {
// VERSIONNUMBER: 'v1',
// RATELIMITSETTINGS: {
// WINDOWMS: 900000,
// MAXREQUESTS: 100
// }
// }
// }
Processing Error Objects
typescript
import { upperize } from 'radash'
const errorObject = {
errorName: 'ValidationError',
errorMessage: 'Invalid input',
errorDetails: {
fieldName: 'email',
fieldValue: 'invalid-email',
validationConstraints: {
format: 'Must be a valid email',
required: true
}
},
errorCode: 'VALIDATION_FAILED'
}
const upperized = upperize(errorObject)
console.log(upperized)
// {
// ERRORNAME: 'ValidationError',
// ERRORMESSAGE: 'Invalid input',
// ERRORDETAILS: {
// FIELDNAME: 'email',
// FIELDVALUE: 'invalid-email',
// VALIDATIONCONSTRAINTS: {
// FORMAT: 'Must be a valid email',
// REQUIRED: true
// }
// },
// ERRORCODE: 'VALIDATION_FAILED'
// }
Processing Log Data
typescript
import { upperize } from 'radash'
const logEntry = {
logTimestamp: new Date(),
logLevel: 'ERROR',
logMessage: 'Database connection failed',
logContext: {
userId: 123,
requestId: 'req_456',
sessionId: 'sess_789'
},
errorInfo: {
errorCode: 'ECONNREFUSED',
errorMessage: 'Connection refused',
stackTrace: 'Error: Connection refused...'
}
}
const upperized = upperize(logEntry)
console.log(upperized)
// {
// LOGTIMESTAMP: 2023-12-31T12:00:00.000Z,
// LOGLEVEL: 'ERROR',
// LOGMESSAGE: 'Database connection failed',
// LOGCONTEXT: {
// USERID: 123,
// REQUESTID: 'req_456',
// SESSIONID: 'sess_789'
// },
// ERRORINFO: {
// ERRORCODE: 'ECONNREFUSED',
// ERRORMESSAGE: 'Connection refused',
// STACKTRACE: 'Error: Connection refused...'
// }
// }
Processing Database Query Results
typescript
import { upperize } from 'radash'
const dbResult = {
recordID: 1,
productName: 'Product A',
categoryInfo: {
categoryID: 5,
categoryName: 'Electronics',
categoryDescription: 'Electronic products'
},
productVariants: [
{ variantID: 101, colorName: 'Red', priceValue: 99.99 },
{ variantID: 102, colorName: 'Blue', priceValue: 89.99 }
],
metadata: {
createdAt: new Date(),
updatedAt: new Date(),
versionNumber: '1.0.0'
}
}
const upperized = upperize(dbResult)
console.log(upperized)
// {
// RECORDID: 1,
// PRODUCTNAME: 'Product A',
// CATEGORYINFO: {
// CATEGORYID: 5,
// CATEGORYNAME: 'Electronics',
// CATEGORYDESCRIPTION: 'Electronic products'
// },
// PRODUCTVARIANTS: [
// { VARIANTID: 101, COLORNAME: 'Red', PRICEVALUE: 99.99 },
// { VARIANTID: 102, COLORNAME: 'Blue', PRICEVALUE: 89.99 }
// ],
// METADATA: {
// CREATEDAT: 2023-12-31T12:00:00.000Z,
// UPDATEDAT: 2023-12-31T12:00:00.000Z,
// VERSIONNUMBER: '1.0.0'
// }
// }
Processing Empty Objects and Edge Cases
typescript
import { upperize } from 'radash'
// Empty object
console.log(upperize({})) // {}
// Single key-value pair
console.log(upperize({ key: 'value' })) // { KEY: 'value' }
// Contains null/undefined values
console.log(upperize({ a: 1, b: null, c: undefined }))
// { A: 1, B: null, C: undefined }
// Keys with special characters
console.log(upperize({ 'user-name': 'Alice', 'email@domain': 'test' }))
// { 'USER-NAME': 'Alice', 'EMAIL@DOMAIN': 'test' }
Processing Complex Nested Objects
typescript
import { upperize } 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,
smsNotifications: true
}
}
},
systemInfo: {
versionNumber: '1.0.0',
environmentType: 'production',
buildInfo: {
buildNumber: '12345',
buildDate: new Date(),
commitHash: 'abc123def456'
}
}
}
const upperized = upperize(complexObj)
console.log(upperized)
// {
// USERPROFILE: {
// PERSONALINFO: {
// FULLNAME: 'Alice Smith',
// AGEVALUE: 25,
// CONTACTDETAILS: {
// EMAILADDRESS: 'alice@example.com',
// PHONENUMBER: '123-456-7890'
// }
// },
// USERSETTINGS: {
// THEMEPREFERENCE: 'dark',
// NOTIFICATIONSETTINGS: {
// EMAILNOTIFICATIONS: true,
// PUSHNOTIFICATIONS: false,
// SMSNOTIFICATIONS: true
// }
// }
// },
// SYSTEMINFO: {
// VERSIONNUMBER: '1.0.0',
// ENVIRONMENTTYPE: 'production',
// BUILDINFO: {
// BUILDNUMBER: '12345',
// BUILDDATE: 2023-12-31T12:00:00.000Z,
// COMMITHASH: 'abc123def456'
// }
// }
// }
Processing Enumeration Maps
typescript
import { upperize } from 'radash'
const statusMap = {
userStatus: {
activeStatus: 'ACTIVE',
inactiveStatus: 'INACTIVE',
pendingStatus: 'PENDING',
suspendedStatus: 'SUSPENDED'
},
orderStatus: {
pendingOrder: 'PENDING',
confirmedOrder: 'CONFIRMED',
shippedOrder: 'SHIPPED',
deliveredOrder: 'DELIVERED'
}
}
const upperized = upperize(statusMap)
console.log(upperized)
// {
// USERSTATUS: {
// ACTIVESTATUS: 'ACTIVE',
// INACTIVESTATUS: 'INACTIVE',
// PENDINGSTATUS: 'PENDING',
// SUSPENDEDSTATUS: 'SUSPENDED'
// },
// ORDERSTATUS: {
// PENDINGORDER: 'PENDING',
// CONFIRMEDORDER: 'CONFIRMED',
// SHIPPEDORDER: 'SHIPPED',
// DELIVEREDORDER: 'DELIVERED'
// }
// }
Processing Color Maps
typescript
import { upperize } from 'radash'
const colorMap = {
primaryColors: {
primaryRed: '#FF0000',
primaryBlue: '#0000FF',
primaryGreen: '#00FF00'
},
secondaryColors: {
secondaryYellow: '#FFFF00',
secondaryPurple: '#800080',
secondaryOrange: '#FFA500'
}
}
const upperized = upperize(colorMap)
console.log(upperized)
// {
// PRIMARYCOLORS: {
// PRIMARYRED: '#FF0000',
// PRIMARYBLUE: '#0000FF',
// PRIMARYGREEN: '#00FF00'
// },
// SECONDARYCOLORS: {
// SECONDARYYELLOW: '#FFFF00',
// SECONDARYPURPLE: '#800080',
// SECONDARYORANGE: '#FFA500'
// }
// }
Notes
- Recursive Processing: Recursively process all nested objects
- Array Processing: Objects within arrays are also processed
- Immutability: Returns a new object, does not modify the original object
- Type Safety: Supports TypeScript type inference
- Special Characters: Preserves special characters in key names (e.g., hyphens, underscores)
Differences from Other Methods
Object.keys()
: Get all keys of an objectupperize()
: Convert key names to uppercaselowerize()
: Convert key names to lowercasemapKeys()
: Custom key name mapping
Practical Applications
- Data Standardization: Standardize the format of object key names
- API Adaptation: Adapt to APIs requiring uppercase key names
- Database Mapping: Map database field names
- Configuration Handling: Handle key name formats in configuration objects
- Data Transformation: Convert key names to uppercase or lowercase