Skip to content

omit

从对象中排除指定的属性,创建新对象。

语法

typescript
omit<T, K extends keyof T>(
  object: T,
  keys: K[]
): Omit<T, K>

参数

  • object (T): 源对象
  • keys (K[]): 要排除的属性键数组

返回值

  • Omit<T, K>: 排除指定属性后的新对象

示例

基本用法

typescript
import { omit } from 'radash'

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

const publicUser = omit(user, ['password', 'email'])
// { id: 1, name: 'Alice', age: 25 }

排除单个属性

typescript
import { omit } from 'radash'

const product = {
  id: 123,
  name: 'Laptop',
  price: 999,
  category: 'Electronics'
}

const productWithoutId = omit(product, ['id'])
// { name: 'Laptop', price: 999, category: 'Electronics' }

排除多个属性

typescript
import { omit } from 'radash'

const order = {
  id: 'ORD-001',
  customerId: 456,
  items: ['item1', 'item2'],
  total: 150.00,
  status: 'pending',
  createdAt: new Date()
}

const orderSummary = omit(order, ['customerId', 'createdAt'])
// { id: 'ORD-001', items: ['item1', 'item2'], total: 150.00, status: 'pending' }

处理嵌套对象

typescript
import { omit } from 'radash'

const user = {
  id: 1,
  profile: {
    firstName: 'Alice',
    lastName: 'Smith',
    age: 25
  },
  settings: {
    theme: 'dark',
    language: 'en'
  }
}

const userWithoutSettings = omit(user, ['settings'])
// { id: 1, profile: { firstName: 'Alice', lastName: 'Smith', age: 25 } }

处理不存在的属性

typescript
import { omit } from 'radash'

const user = {
  name: 'Alice',
  age: 25
}

const result = omit(user, ['name', 'email', 'age'])
// {} (所有属性都被排除)

处理空对象

typescript
import { omit } from 'radash'

const emptyObj = {}
const result = omit(emptyObj, ['name', 'age'])
// {}

处理空键数组

typescript
import { omit } from 'radash'

const user = {
  name: 'Alice',
  age: 25
}

const result = omit(user, [])
// { name: 'Alice', age: 25 } (没有排除任何属性)

处理函数属性

typescript
import { omit } from 'radash'

const component = {
  name: 'Button',
  render: () => '<button>Click me</button>',
  props: { text: 'Click me' }
}

const componentWithoutRender = omit(component, ['render'])
// { name: 'Button', props: { text: 'Click me' } }

处理数组属性

typescript
import { omit } from 'radash'

const user = {
  id: 1,
  name: 'Alice',
  hobbies: ['reading', 'swimming'],
  tags: ['developer', 'frontend']
}

const userWithoutHobbies = omit(user, ['hobbies'])
// { id: 1, name: 'Alice', tags: ['developer', 'frontend'] }

处理日期属性

typescript
import { omit } from 'radash'

const event = {
  id: 1,
  title: 'Meeting',
  date: new Date('2023-01-01'),
  duration: 60,
  attendees: ['Alice', 'Bob']
}

const eventWithoutDate = omit(event, ['date'])
// { id: 1, title: 'Meeting', duration: 60, attendees: ['Alice', 'Bob'] }

处理布尔值属性

typescript
import { omit } from 'radash'

const user = {
  id: 1,
  name: 'Alice',
  isActive: true,
  isAdmin: false,
  email: 'alice@example.com'
}

const userWithoutStatus = omit(user, ['isActive', 'isAdmin'])
// { id: 1, name: 'Alice', email: 'alice@example.com' }

处理null和undefined值

typescript
import { omit } from 'radash'

const user = {
  name: 'Alice',
  email: null,
  phone: undefined,
  age: 25
}

const userWithoutNulls = omit(user, ['email', 'phone'])
// { name: 'Alice', age: 25 }

处理Symbol属性

typescript
import { omit } from 'radash'

const sym = Symbol('key')

const obj = {
  [sym]: 'value',
  name: 'Alice',
  age: 25
}

const result = omit(obj, [sym, 'name'])
// { age: 25 }

处理复杂对象

typescript
import { omit } from 'radash'

const complexObject = {
  id: 1,
  metadata: {
    createdAt: new Date(),
    version: '1.0.0'
  },
  data: {
    items: [1, 2, 3],
    total: 100
  },
  config: {
    theme: 'dark',
    language: 'en'
  }
}

const essentialData = omit(complexObject, ['metadata', 'config'])
// { id: 1, data: { items: [1, 2, 3], total: 100 } }

处理API响应

typescript
import { omit } from 'radash'

const apiResponse = {
  data: {
    users: [
      { id: 1, name: 'Alice', email: 'alice@example.com' },
      { id: 2, name: 'Bob', email: 'bob@example.com' }
    ],
    total: 2,
    page: 1,
    limit: 10
  },
  status: 200,
  message: 'Success',
  timestamp: new Date()
}

const userData = omit(apiResponse, ['status', 'message', 'timestamp'])
// { data: { users: [...], total: 2, page: 1, limit: 10 } }

处理表单数据

typescript
import { omit } from 'radash'

const formData = {
  firstName: 'Alice',
  lastName: 'Smith',
  email: 'alice@example.com',
  password: 'secret123',
  confirmPassword: 'secret123',
  terms: true
}

const publicInfo = omit(formData, ['password', 'confirmPassword', 'terms'])
// { firstName: 'Alice', lastName: 'Smith', email: 'alice@example.com' }

数据清理

typescript
import { omit } from 'radash'

function cleanSensitiveData(data: any) {
  const sensitiveFields = ['password', 'token', 'secret', 'privateKey']
  return omit(data, sensitiveFields)
}

const userData = {
  id: 1,
  name: 'Alice',
  email: 'alice@example.com',
  password: 'secret123',
  token: 'abc123',
  preferences: { theme: 'dark' }
}

const cleanData = cleanSensitiveData(userData)
// { id: 1, name: 'Alice', email: 'alice@example.com', preferences: { theme: 'dark' } }

条件排除

typescript
import { omit } from 'radash'

function createUserResponse(user: any, includePrivate = false) {
  const privateFields = ['password', 'email', 'phone']
  
  if (includePrivate) {
    return user
  }
  
  return omit(user, privateFields)
}

const user = {
  id: 1,
  name: 'Alice',
  email: 'alice@example.com',
  password: 'secret123',
  phone: '123-456-7890'
}

const publicResponse = createUserResponse(user, false)
// { id: 1, name: 'Alice' }

const privateResponse = createUserResponse(user, true)
// { id: 1, name: 'Alice', email: 'alice@example.com', password: 'secret123', phone: '123-456-7890' }

注意事项

  1. 不可变性: 不会修改原对象
  2. 类型安全: 支持完整的 TypeScript 类型推断
  3. 不存在的属性: 会忽略不存在的属性
  4. 浅拷贝: 只进行浅拷贝,嵌套对象会共享引用

与其他函数的区别

  • omit: 排除指定的属性
  • pick: 选择指定的属性
  • keys: 获取对象的所有键
  • values: 获取对象的所有值

性能

  • 时间复杂度: O(n),其中 n 是键的数量
  • 空间复杂度: O(n)
  • 适用场景: 数据过滤、隐私保护、API响应处理

Released under the MIT License.