Omit Function
Data Manipulation7 functions
Utility Overview
Details
Creates new objects by excluding specified properties, supporting various filtering strategies including nested paths and predicates
Category:Data Manipulation
Functions:omit, omitSingle, omitDeep, omitBy, omitKeys, omitByType, omitByPattern
Performance:
- Time: O(n) where n is source object properties - Space: O(k) where k is result object properties
Concepts:
object manipulationproperty filteringimmutabilitytype safety
Implementation
omit
Time: O(n) | Space: O(k)
export function omit<T extends Record<string, unknown>, K extends keyof T>(
obj: T,
keys: K[]
): Omit<T, K> {
if (obj == null || typeof obj !== 'object') {
throw new Error('First argument must be an object');
}
if (!Array.isArray(keys)) {
throw new Error('Second argument must be an array of keys');
}
const result = {} as Omit<T, K>;
const keysToOmit = new Set(keys);
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && !keysToOmit.has(key as unknown as K)) {
(result as Record<string, unknown>)[key] = obj[key];
}
}
return result;
}
// Omit with single key (convenience overload)Usage Examples
Basic property omission
const user = {
id: 1,
name: 'John Doe',
email: 'john@example.com',
password: 'secret123',
role: 'admin',
createdAt: '2024-01-01'
};
// Remove sensitive information
const publicUser = omit(user, ['password']);
console.log(publicUser);
// { id: 1, name: 'John Doe', email: 'john@example.com', role: 'admin', createdAt: '2024-01-01' }
// Remove multiple properties
const basicUser = omit(user, ['password', 'role', 'createdAt']);
console.log(basicUser);
// { id: 1, name: 'John Doe', email: 'john@example.com' }
// Convenience method for single key
const withoutEmail = omitSingle(user, 'email');
console.log(withoutEmail);
// { id: 1, name: 'John Doe', password: 'secret123', role: 'admin', createdAt: '2024-01-01' }API response sanitization and filtering
interface ApiResponse {
success: boolean;
data: {
user: {
id: number;
name: string;
email: string;
internalId: string;
debug: any;
};
metadata: {
requestId: string;
timestamp: string;
version: string;
debug: any;
};
};
debug: any;
internalFields: any;
}
const apiResponse: ApiResponse = {
success: true,
data: {
user: {
id: 1,
name: 'John',
email: 'john@example.com',
internalId: 'internal-123',
debug: { trace: 'xyz' }
},
metadata: {
requestId: 'req-456',
timestamp: '2024-01-01',
version: '1.0',
debug: { performance: '100ms' }
}
},
debug: { sql: 'SELECT * FROM users' },
internalFields: { cache: 'hit' }
};
// Remove debug and internal fields
const cleanResponse = omit(apiResponse, ['debug', 'internalFields']);
// Remove nested debug fields
const deepCleanResponse = omitDeep(cleanResponse, [
'data.user.debug',
'data.user.internalId',
'data.metadata.debug'
]);
console.log(deepCleanResponse);
// Clean response without any debug or internal informationConditional property omission with predicates
const formData = {
name: 'John',
email: 'john@example.com',
age: 30,
phone: '',
address: null,
newsletter: false,
terms: true,
comments: undefined,
score: 0
};
// Remove empty/null/undefined values
const nonEmptyData = omitBy(formData, (value) => {
return value === null || value === undefined || value === '';
});
console.log(nonEmptyData);
// { name: 'John', email: 'john@example.com', age: 30, newsletter: false, terms: true, score: 0 }
// Remove false boolean values only
const truthyBooleans = omitBy(formData, (value, key) => {
return typeof value === 'boolean' && value === false;
});
// Remove by type
const noStrings = omitByType(formData, ['string']);
console.log(noStrings);
// { age: 30, address: null, newsletter: false, terms: true, score: 0 }
// Remove by pattern (fields ending with 'Id' or containing 'temp')
const config = {
userId: 123,
userName: 'john',
tempData: 'cache',
apiKey: 'secret',
tempConfig: 'dev',
sessionId: 'abc123'
};
const filtered = omitByPattern(config, [/Id$/, /temp/i]);
console.log(filtered);
// { userName: 'john', apiKey: 'secret' }Form data processing and validation preparation
interface FormInput {
// User fields
firstName: string;
lastName: string;
email: string;
phone: string;
// UI state (should not be sent to API)
isLoading: boolean;
showPassword: boolean;
formTouched: boolean;
// Validation fields (internal use)
firstNameError?: string;
lastNameError?: string;
emailError?: string;
// Meta fields
timestamp: string;
userAgent: string;
}
const formInput: FormInput = {
firstName: 'John',
lastName: 'Doe',
email: 'john@example.com',
phone: '+1234567890',
isLoading: false,
showPassword: false,
formTouched: true,
firstNameError: undefined,
emailError: 'Invalid format',
timestamp: '2024-01-01T10:00:00Z',
userAgent: 'Mozilla/5.0...'
};
// Prepare data for API submission (remove UI state and validation fields)
const apiData = omitByPattern(formInput, [
/^is[A-Z]/, // Remove isLoading, etc.
/^show[A-Z]/, // Remove showPassword, etc.
/Error$/, // Remove validation errors
/^form[A-Z]/ // Remove formTouched, etc.
]);
// Further clean for specific endpoint
const userOnlyData = omit(apiData, ['timestamp', 'userAgent']);
console.log(userOnlyData);
// { firstName: 'John', lastName: 'Doe', email: 'john@example.com', phone: '+1234567890' }
// Create analytics data (keep only meta fields)
const analyticsData = omitBy(formInput, (value, key) => {
const metaFields = ['timestamp', 'userAgent', 'formTouched'];
return !metaFields.includes(String(key));
});