or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

array.mdcompat.mderror.mdfunction.mdindex.mdmath.mdobject.mdpredicate.mdpromise.mdstring.mdutil.md
tile.json

object.mddocs/

Object Utilities

Comprehensive object manipulation functions for property selection, transformation, merging, cloning, and analysis. All functions maintain strong TypeScript type safety and support both shallow and deep operations.

Capabilities

Property Selection and Filtering

Functions for selecting or excluding object properties based on keys or predicates.

/**
 * Creates object with only specified properties
 * @param obj - Source object
 * @param keys - Array of property keys to include
 * @returns New object with only specified properties
 */
function pick<T, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K>;

/**
 * Creates object excluding specified properties
 * @param obj - Source object
 * @param keys - Array of property keys to exclude
 * @returns New object without specified properties
 */
function omit<T, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K>;

/**
 * Picks properties that satisfy predicate function
 * @param obj - Source object
 * @param shouldPick - Predicate function for property selection
 * @returns New object with properties that satisfy predicate
 */
function pickBy<T>(
  obj: T, 
  shouldPick: (value: T[keyof T], key: keyof T) => boolean
): Partial<T>;

/**
 * Omits properties that satisfy predicate function
 * @param obj - Source object
 * @param shouldOmit - Predicate function for property exclusion
 * @returns New object without properties that satisfy predicate
 */
function omitBy<T>(
  obj: T, 
  shouldOmit: (value: T[keyof T], key: keyof T) => boolean
): Partial<T>;

Usage Examples:

import { pick, omit, pickBy, omitBy } from 'es-toolkit/object';

const user = {
  id: 1,
  name: 'Alice',
  email: 'alice@example.com',
  password: 'secret123',
  age: 25,
  isActive: true
};

// Select specific properties
const publicUser = pick(user, ['id', 'name', 'email']);
console.log(publicUser); // { id: 1, name: 'Alice', email: 'alice@example.com' }

// Exclude sensitive properties
const safeUser = omit(user, ['password']);
console.log(safeUser); // { id: 1, name: 'Alice', email: '...', age: 25, isActive: true }

// Pick properties based on condition
const stringProps = pickBy(user, (value) => typeof value === 'string');
console.log(stringProps); // { name: 'Alice', email: '...', password: 'secret123' }

// Omit properties based on condition
const nonStringProps = omitBy(user, (value) => typeof value === 'string');
console.log(nonStringProps); // { id: 1, age: 25, isActive: true }

Object Transformation

Functions for transforming object keys and values while preserving or modifying structure.

/**
 * Creates object with transformed keys
 * @param object - Source object
 * @param getNewKey - Function to transform keys
 * @returns New object with transformed keys
 */
function mapKeys<T, K extends keyof T, V extends PropertyKey>(
  object: T, 
  getNewKey: (value: T[K], key: K, object: T) => V
): Record<V, T[K]>;

/**
 * Creates object with transformed values
 * @param object - Source object
 * @param getNewValue - Function to transform values
 * @returns New object with same keys but transformed values
 */
function mapValues<T, K extends keyof T, V>(
  object: T, 
  getNewValue: (value: T[K], key: K, object: T) => V
): Record<K, V>;

/**
 * Creates inverted object where values become keys
 * @param obj - Source object
 * @returns Object with keys and values swapped
 */
function invert<T extends Record<PropertyKey, PropertyKey>>(
  obj: T
): { [K in keyof T as T[K]]: K };

/**
 * Flattens nested object into flat structure with dot notation
 * @param object - Object to flatten
 * @param prefix - Optional prefix for keys
 * @returns Flattened object with dot-separated keys
 */
function flattenObject<T extends Record<string, any>>(
  object: T, 
  prefix?: string
): Record<string, any>;

Usage Examples:

import { mapKeys, mapValues, invert, flattenObject } from 'es-toolkit/object';

const data = {
  firstName: 'Alice',
  lastName: 'Johnson',
  age: 30
};

// Transform keys to uppercase
const upperKeys = mapKeys(data, (value, key) => key.toUpperCase());
console.log(upperKeys); // { FIRSTNAME: 'Alice', LASTNAME: 'Johnson', AGE: 30 }

// Transform values to strings
const stringValues = mapValues(data, (value) => String(value));
console.log(stringValues); // { firstName: 'Alice', lastName: 'Johnson', age: '30' }

// Invert object
const roles = { admin: 'Alice', user: 'Bob', guest: 'Charlie' };
const inverted = invert(roles);
console.log(inverted); // { Alice: 'admin', Bob: 'user', Charlie: 'guest' }

// Flatten nested object
const nested = {
  user: {
    profile: {
      name: 'Alice',
      settings: { theme: 'dark' }
    }
  }
};
const flattened = flattenObject(nested);
console.log(flattened); // { 'user.profile.name': 'Alice', 'user.profile.settings.theme': 'dark' }

Object Merging

Functions for combining objects with various merge strategies including deep merging and custom merge logic.

/**
 * Deep merges source object into target object (mutating)
 * @param target - Target object to merge into
 * @param source - Source object to merge from
 * @returns Merged object (mutated target)
 */
function merge<T, S>(target: T, source: S): T & S;

/**
 * Deep merges with custom merger function (mutating)
 * @param target - Target object to merge into
 * @param source - Source object to merge from
 * @param merger - Custom function to handle merge conflicts
 * @returns Merged object (mutated target)
 */
function mergeWith<T, S>(
  target: T, 
  source: S, 
  merger: (targetValue: any, sourceValue: any, key: string, target: T, source: S) => any
): T & S;

/**
 * Creates merged object without mutating inputs (non-mutating)
 * @param target - Target object
 * @param source - Source object
 * @returns New merged object
 */
function toMerged<T, S>(target: T, source: S): T & S;

Usage Examples:

import { merge, mergeWith, toMerged } from 'es-toolkit/object';

const defaults = {
  timeout: 5000,
  retries: 3,
  headers: { 'Content-Type': 'application/json' }
};

const userConfig = {
  timeout: 10000,
  headers: { 'Authorization': 'Bearer token' }
};

// Deep merge (mutating)
const config1 = merge({ ...defaults }, userConfig);
console.log(config1);
// { timeout: 10000, retries: 3, headers: { 'Content-Type': '...', 'Authorization': '...' } }

// Non-mutating merge
const config2 = toMerged(defaults, userConfig);
console.log(config2); // Same result, but defaults unchanged

// Custom merge logic
const arrayMerger = (targetValue: any, sourceValue: any) => {
  if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
    return [...targetValue, ...sourceValue];
  }
  return undefined; // Use default merge behavior
};

const obj1 = { tags: ['frontend'], count: 1 };
const obj2 = { tags: ['react'], count: 2 };
const merged = mergeWith(obj1, obj2, arrayMerger);
console.log(merged); // { tags: ['frontend', 'react'], count: 2 }

Object Cloning

Functions for creating shallow and deep copies of objects with support for complex data types.

/**
 * Creates shallow clone of object
 * @param obj - Object to clone
 * @returns Shallow clone of the object
 */
function clone<T>(obj: T): T;

/**
 * Creates deep clone of object
 * @param obj - Object to clone
 * @returns Deep clone of the object
 */
function cloneDeep<T>(obj: T): T;

/**
 * Creates deep clone with custom cloning function
 * @param obj - Object to clone
 * @param cloneFunction - Optional custom cloning function
 * @returns Deep clone of the object
 */
function cloneDeepWith<T>(
  obj: T, 
  cloneFunction?: (value: any, key: string | number, object: any, stack: Map<any, any>) => any
): T;

Usage Examples:

import { clone, cloneDeep, cloneDeepWith } from 'es-toolkit/object';

const original = {
  name: 'Alice',
  details: {
    age: 30,
    hobbies: ['reading', 'coding'],
    address: { city: 'New York', zip: '10001' }
  },
  createdAt: new Date()
};

// Shallow clone - nested objects are still referenced
const shallowCopy = clone(original);
shallowCopy.details.age = 31; // This affects original.details.age

// Deep clone - completely independent copy
const deepCopy = cloneDeep(original);
deepCopy.details.age = 25; // Original is unaffected

// Custom deep clone with special handling
const customClone = cloneDeepWith(original, (value) => {
  if (value instanceof Date) {
    return new Date(value.getTime() + 86400000); // Add one day
  }
  return undefined; // Use default cloning
});

Object Analysis

Functions for analyzing object structure and finding specific properties or values.

/**
 * Finds first property key that satisfies predicate
 * @param obj - Object to search
 * @param predicate - Function to test properties
 * @returns First key that satisfies predicate or undefined
 */
function findKey<T>(
  obj: T, 
  predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean
): keyof T | undefined;

Usage Examples:

import { findKey } from 'es-toolkit/object';

const inventory = {
  apples: 10,
  bananas: 0,
  oranges: 5,
  grapes: 0
};

// Find first property with zero value
const emptyStock = findKey(inventory, (value) => value === 0);
console.log(emptyStock); // 'bananas'

// Find first property with non-zero value
const availableItem = findKey(inventory, (value) => value > 0);
console.log(availableItem); // 'apples'

Case Conversion

Functions for converting object property names between different case formats.

/**
 * Converts all object keys to camelCase
 * @param obj - Object with keys to convert
 * @returns New object with camelCase keys
 */
function toCamelCaseKeys<T>(obj: T): T;

/**
 * Converts all object keys to snake_case
 * @param obj - Object with keys to convert
 * @returns New object with snake_case keys
 */
function toSnakeCaseKeys<T>(obj: T): T;

Usage Examples:

import { toCamelCaseKeys, toSnakeCaseKeys } from 'es-toolkit/object';

// Convert API response from snake_case to camelCase
const apiResponse = {
  user_id: 123,
  first_name: 'Alice',
  last_name: 'Johnson',
  created_at: '2023-01-01',
  user_preferences: {
    email_notifications: true,
    dark_mode: false
  }
};

const camelCased = toCamelCaseKeys(apiResponse);
console.log(camelCased);
/*
{
  userId: 123,
  firstName: 'Alice',
  lastName: 'Johnson',
  createdAt: '2023-01-01',
  userPreferences: {
    emailNotifications: true,
    darkMode: false
  }
}
*/

// Convert JavaScript object to snake_case for API
const jsObject = {
  userId: 456,
  firstName: 'Bob',
  profileSettings: {
    enableNotifications: true,
    preferredLanguage: 'en'
  }
};

const snakeCased = toSnakeCaseKeys(jsObject);
console.log(snakeCased);
/*
{
  user_id: 456,
  first_name: 'Bob',
  profile_settings: {
    enable_notifications: true,
    preferred_language: 'en'
  }
}
*/

Supported Data Types

ES-Toolkit's object utilities work with a wide range of JavaScript data types:

  • Plain Objects: Standard JavaScript objects
  • Arrays: Handled appropriately in merge and clone operations
  • Dates: Properly cloned with correct date values
  • RegExp: Cloned with same pattern and flags
  • Maps and Sets: Deep cloning preserves collection contents
  • Nested Structures: Full support for deeply nested objects
  • Circular References: Handled safely in deep operations
  • Functions: Preserved in clone operations
  • Primitives: Numbers, strings, booleans, null, undefined

Performance Characteristics

  • Memory Efficient: Optimized algorithms minimize memory allocation
  • Type Safe: Full TypeScript support with preserved generics
  • Immutable by Default: Most operations return new objects
  • Deep Operation Support: Efficient handling of nested structures
  • Modern JavaScript: Leverages ES6+ features for performance