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' }
// ]
注意事項
- 默認格式: 默認返回
{ key, value }
對象數組 - 自定義轉換: 可以通過
toItem
參數自定義每個數組項的結構 - 空對象: 空對象返回空數組
- 不可變性: 返回新數組,不修改原對象
- 類型安全: 支持TypeScript類型推斷
與其他方法的區別
Object.entries()
: 返回[key, value]
數組Object.keys()
: 只返回鍵數組Object.values()
: 只返回值數組listify()
: 返回{ key, value }
對象數組
實際應用場景
- 表格數據: 將對象轉換為表格行數據
- 選項列表: 創建下拉菜單或選擇器選項
- 配置展示: 展示配置對象的鍵值對
- 數據轉換: 在數據處理中轉換對象結構
- API響應: 處理API響應的鍵值對展示