Skip to main content

Convert Object Values

convertObjectValues

Converts specified values in objects or arrays of objects between string and number types, supporting nested properties via dot notation.

Import

import { convertObjectValues } from 'nhb-toolbox';

Function Signatures

// Object version
convertObjectValues<
T extends GenericObject,
Key extends NumericDotKey<T>,
C extends 'string' | 'number',
>(data: T, options: ConvertObjectOptions<T, Key, C>): ConvertedObject<T, Key, C>;

// Array version
convertObjectValues<
T extends GenericObject,
Key extends NumericDotKey<T>,
C extends 'string' | 'number',
>(data: Array<T>, options: ConvertObjectOptions<T, Key, C>): Array<ConvertedObject<T, Key, C>>;

Usage Examples

Convert to Numbers

const product = {
id: "123",
price: "99.99",
meta: { weight: "1.5" }
};

const result = convertObjectValues(product, {
keys: ['price', 'meta.weight'],
convertTo: 'number'
});
// Returns { id: "123", price: 99.99, meta: { weight: 1.5 } }
// Type: Numberified<typeof product>

Convert to Strings

const user = {
id: 456,
profile: { age: 30 }
};

convertObjectValues(user, {
keys: ['id', 'profile.age'],
convertTo: 'string'
});
// Returns { id: "456", profile: { age: "30" } }
// Type: Stringified<typeof user>

Behavior Details

  1. Dot Notation: Supports nested paths like 'user.profile.age'
  2. Type Safety: Maintains proper TypeScript types in return value
  3. Non-Destructive: Returns new object/array without modifying original
  4. Selective Conversion: Only converts specified fields (only string, number, undefined fields are allowed), all others remain unchanged. Only allows the keys which are typed as number, string or undefined.
  5. Array Support: Works with arrays of objects but only the top level (no nested array conversion is allowed)

Limitations

  1. Circular References: May cause stack overflow for deeply nested objects and arrays
  2. Special Types: Date, RegExp etc. are preserved as-is and are not included in keys array if they are nested within objects
  3. Invalid Numbers: String values that can't convert to numbers are preserved
  4. Performance: Deep cloning may be slow for large structures
  • API response normalization
  • Form data processing
  • Database record preparation
  • Configuration transformation
  • Data migration scripts

Type Definitions

ConvertObjectOptions

interface ConvertObjectOptions<
T extends GenericObject,
Key extends NumericDotKey<T>,
C extends 'string' | 'number',
> {
/** Array of keys (properties) to convert to `number` or `string` */
keys: ValidArray<Key>;
/** Convert selected keys to target type: `number` or `string` */
convertTo: C;
}