Skip to content

listify

将对象转换为键值对列表。

基础用法

typescript
import { listify } from 'radash'

const obj = { name: 'Alice', age: 25, city: 'Beijing' }
const list = listify(obj)
console.log(list) // [{ key: 'name', value: 'Alice' }, { key: 'age', value: 25 }, { key: 'city', value: 'Beijing' }]

语法

typescript
function listify<T extends Record<string, any>>(
  obj: T,
  toItem?: (key: keyof T, value: T[keyof T]) => any
): any[]

参数

  • obj (T): 要转换的对象
  • toItem (可选): 自定义转换函数,用于定义每个数组项的结构

返回值

返回键值对数组,默认格式为 { key, value } 对象数组。

示例

基本转换

typescript
import { listify } from 'radash'

const obj = { name: 'Alice', age: 25, city: 'Beijing' }
const list = listify(obj)
console.log(list)
// [
//   { key: 'name', value: 'Alice' },
//   { key: 'age', value: 25 },
//   { key: 'city', value: 'Beijing' }
// ]

自定义转换函数

typescript
import { listify } from 'radash'

const obj = { name: 'Alice', age: 25, city: 'Beijing' }

// 转换为 [key, value] 数组
const list1 = listify(obj, (key, value) => [key, value])
console.log(list1)
// [['name', 'Alice'], ['age', 25], ['city', 'Beijing']]

// 转换为自定义对象
const list2 = listify(obj, (key, value) => ({
  id: key,
  data: value,
  type: typeof value
}))
console.log(list2)
// [
//   { id: 'name', data: 'Alice', type: 'string' },
//   { id: 'age', data: 25, type: 'number' },
//   { id: 'city', data: 'Beijing', type: 'string' }
// ]

处理不同类型的值

typescript
import { listify } from 'radash'

const obj = {
  name: 'Alice',
  age: 25,
  isActive: true,
  score: 95.5,
  tags: ['admin', 'user'],
  metadata: { id: 1 }
}

const list = listify(obj)
console.log(list)
// [
//   { key: 'name', value: 'Alice' },
//   { key: 'age', value: 25 },
//   { key: 'isActive', value: true },
//   { key: 'score', value: 95.5 },
//   { key: 'tags', value: ['admin', 'user'] },
//   { key: 'metadata', value: { id: 1 } }
// ]

处理空值和undefined

typescript
import { listify } from 'radash'

const obj = {
  name: 'Alice',
  email: null,
  phone: undefined,
  address: ''
}

const list = listify(obj)
console.log(list)
// [
//   { key: 'name', value: 'Alice' },
//   { key: 'email', value: null },
//   { key: 'phone', value: undefined },
//   { key: 'address', value: '' }
// ]

处理嵌套对象

typescript
import { listify } from 'radash'

const obj = {
  user: { name: 'Alice', age: 25 },
  settings: { theme: 'dark', language: 'en' }
}

const list = listify(obj)
console.log(list)
// [
//   { key: 'user', value: { name: 'Alice', age: 25 } },
//   { key: 'settings', value: { theme: 'dark', language: 'en' } }
// ]

处理函数值

typescript
import { listify } from 'radash'

const obj = {
  name: 'Alice',
  handler: () => 'hello',
  validator: function() { return true },
  processor: (x: number) => x * 2
}

const list = listify(obj)
console.log(list)
// [
//   { key: 'name', value: 'Alice' },
//   { key: 'handler', value: [Function: handler] },
//   { key: 'validator', value: [Function: validator] },
//   { key: 'processor', value: [Function: processor] }
// ]

处理日期值

typescript
import { listify } from 'radash'

const obj = {
  createdAt: new Date('2023-01-01'),
  updatedAt: new Date('2023-12-31'),
  birthday: new Date('1998-05-15')
}

const list = listify(obj)
console.log(list)
// [
//   { key: 'createdAt', value: 2023-01-01T00:00:00.000Z },
//   { key: 'updatedAt', value: 2023-12-31T00:00:00.000Z },
//   { key: 'birthday', value: 1998-05-15T00:00:00.000Z }
// ]

处理配置对象

typescript
import { listify } from 'radash'

const config = {
  server: {
    host: 'localhost',
    port: 3000
  },
  database: {
    url: 'postgresql://localhost:5432/mydb',
    pool: { min: 1, max: 10 }
  },
  api: {
    version: 'v1',
    rateLimit: { windowMs: 900000, max: 100 }
  }
}

const list = listify(config)
console.log(list)
// [
//   { key: 'server', value: { host: 'localhost', port: 3000 } },
//   { key: 'database', value: { url: 'postgresql://localhost:5432/mydb', pool: { min: 1, max: 10 } } },
//   { key: 'api', value: { version: 'v1', rateLimit: { windowMs: 900000, max: 100 } } }
// ]

处理API响应数据

typescript
import { listify } from 'radash'

const apiResponse = {
  status: 200,
  data: { id: 1, name: 'Alice' },
  meta: { timestamp: new Date(), requestId: 'req_123456' }
}

const list = listify(apiResponse)
console.log(list)
// [
//   { key: 'status', value: 200 },
//   { key: 'data', value: { id: 1, name: 'Alice' } },
//   { key: 'meta', value: { timestamp: 2023-12-31T12:00:00.000Z, requestId: 'req_123456' } }
// ]

处理表单数据

typescript
import { listify } from 'radash'

const formData = {
  personal: {
    firstName: 'Alice',
    lastName: 'Smith',
    email: 'alice@example.com'
  },
  address: {
    street: '123 Main St',
    city: 'Beijing',
    country: 'China'
  },
  preferences: {
    newsletter: true,
    notifications: { email: true, sms: false }
  }
}

const list = listify(formData)
console.log(list)
// [
//   { key: 'personal', value: { firstName: 'Alice', lastName: 'Smith', email: 'alice@example.com' } },
//   { key: 'address', value: { street: '123 Main St', city: 'Beijing', country: 'China' } },
//   { key: 'preferences', value: { newsletter: true, notifications: { email: true, sms: false } } }
// ]

处理错误对象

typescript
import { listify } from 'radash'

const errorObject = {
  name: 'ValidationError',
  message: 'Invalid input',
  details: {
    field: 'email',
    value: 'invalid-email',
    constraints: { format: 'Must be a valid email' }
  }
}

const list = listify(errorObject)
console.log(list)
// [
//   { key: 'name', value: 'ValidationError' },
//   { key: 'message', value: 'Invalid input' },
//   { key: 'details', value: { field: 'email', value: 'invalid-email', constraints: { format: 'Must be a valid email' } } }
// ]

处理日志数据

typescript
import { listify } from 'radash'

const logEntry = {
  timestamp: new Date(),
  level: 'ERROR',
  message: 'Database connection failed',
  context: { userId: 123, requestId: 'req_456' },
  error: { code: 'ECONNREFUSED', message: 'Connection refused' }
}

const list = listify(logEntry)
console.log(list)
// [
//   { key: 'timestamp', value: 2023-12-31T12:00:00.000Z },
//   { key: 'level', value: 'ERROR' },
//   { key: 'message', value: 'Database connection failed' },
//   { key: 'context', value: { userId: 123, requestId: 'req_456' } },
//   { key: 'error', value: { code: 'ECONNREFUSED', message: 'Connection refused' } }
// ]

自定义转换示例

typescript
import { listify } from 'radash'

const obj = { name: 'Alice', age: 25, city: 'Beijing' }

// 转换为表格行数据
const tableRows = listify(obj, (key, value) => ({
  column: key,
  value: value,
  type: typeof value
}))
console.log(tableRows)
// [
//   { column: 'name', value: 'Alice', type: 'string' },
//   { column: 'age', value: 25, type: 'number' },
//   { column: 'city', value: 'Beijing', type: 'string' }
// ]

// 转换为选项数据
const options = listify(obj, (key, value) => ({
  label: key,
  value: value,
  disabled: false
}))
console.log(options)
// [
//   { label: 'name', value: 'Alice', disabled: false },
//   { label: 'age', value: 25, disabled: false },
//   { label: 'city', value: 'Beijing', disabled: false }
// ]

// 转换为键值对字符串
const keyValuePairs = listify(obj, (key, value) => `${key}=${value}`)
console.log(keyValuePairs)
// ['name=Alice', 'age=25', 'city=Beijing']

处理空对象和边界情况

typescript
import { listify } from 'radash'

// 空对象
console.log(listify({})) // []

// 只有一个键值对
console.log(listify({ key: 'value' }))
// [{ key: 'key', value: 'value' }]

// 包含空值
console.log(listify({ a: 1, b: null, c: undefined }))
// [
//   { key: 'a', value: 1 },
//   { key: 'b', value: null },
//   { key: 'c', value: undefined }
// ]

处理复杂嵌套对象

typescript
import { listify } from 'radash'

const complexObj = {
  user: {
    profile: {
      name: 'Alice',
      age: 25,
      contact: {
        email: 'alice@example.com',
        phone: '123-456-7890'
      }
    },
    settings: {
      theme: 'dark',
      notifications: {
        email: true,
        push: false
      }
    }
  },
  system: {
    version: '1.0.0',
    environment: 'production',
    features: ['feature1', 'feature2']
  }
}

const list = listify(complexObj)
console.log(list)
// [
//   { key: 'user', value: { profile: { name: 'Alice', age: 25, contact: { email: 'alice@example.com', phone: '123-456-7890' } }, settings: { theme: 'dark', notifications: { email: true, push: false } } } },
//   { key: 'system', value: { version: '1.0.0', environment: 'production', features: ['feature1', 'feature2'] } }
// ]

处理数据库查询结果

typescript
import { listify } from 'radash'

const dbResult = {
  id: 1,
  name: 'Product A',
  category: {
    id: 5,
    name: 'Electronics'
  },
  variants: [
    { id: 101, color: 'Red', price: 99.99 },
    { id: 102, color: 'Blue', price: 89.99 }
  ]
}

const list = listify(dbResult)
console.log(list)
// [
//   { key: 'id', value: 1 },
//   { key: 'name', value: 'Product A' },
//   { key: 'category', value: { id: 5, name: 'Electronics' } },
//   { key: 'variants', value: [{ id: 101, color: 'Red', price: 99.99 }, { id: 102, color: 'Blue', price: 89.99 }] }
// ]

处理枚举映射

typescript
import { listify } from 'radash'

const statusMap = {
  active: 'ACTIVE',
  inactive: 'INACTIVE',
  pending: 'PENDING',
  suspended: 'SUSPENDED'
}

const list = listify(statusMap)
console.log(list)
// [
//   { key: 'active', value: 'ACTIVE' },
//   { key: 'inactive', value: 'INACTIVE' },
//   { key: 'pending', value: 'PENDING' },
//   { key: 'suspended', value: 'SUSPENDED' }
// ]

处理颜色映射

typescript
import { listify } from 'radash'

const colorMap = {
  red: '#FF0000',
  green: '#00FF00',
  blue: '#0000FF',
  yellow: '#FFFF00',
  purple: '#800080'
}

const list = listify(colorMap)
console.log(list)
// [
//   { key: 'red', value: '#FF0000' },
//   { key: 'green', value: '#00FF00' },
//   { key: 'blue', value: '#0000FF' },
//   { key: 'yellow', value: '#FFFF00' },
//   { key: 'purple', value: '#800080' }
// ]

处理语言映射

typescript
import { listify } from 'radash'

const languageMap = {
  'en': 'English',
  'zh': '中文',
  'es': 'Español',
  'fr': 'Français',
  'de': 'Deutsch'
}

const list = listify(languageMap)
console.log(list)
// [
//   { key: 'en', value: 'English' },
//   { key: 'zh', value: '中文' },
//   { key: 'es', value: 'Español' },
//   { key: 'fr', value: 'Français' },
//   { key: 'de', value: 'Deutsch' }
// ]

注意事项

  1. 默认格式: 默认返回 { key, value } 对象数组
  2. 自定义转换: 可以通过 toItem 参数自定义每个数组项的结构
  3. 空对象: 空对象返回空数组
  4. 不可变性: 返回新数组,不修改原对象
  5. 类型安全: 支持TypeScript类型推断

与其他方法的区别

  • Object.entries(): 返回 [key, value] 数组
  • Object.keys(): 只返回键数组
  • Object.values(): 只返回值数组
  • listify(): 返回 { key, value } 对象数组

实际应用场景

  1. 表格数据: 将对象转换为表格行数据
  2. 选项列表: 创建下拉菜单或选择器选项
  3. 配置展示: 展示配置对象的键值对
  4. 数据转换: 在数据处理中转换对象结构
  5. API响应: 处理API响应的键值对展示

Released under the MIT License.