Skip to content

@pmun/utils / invert

Function: invert()

ts
function invert<T>(obj): Record<string, string>;

反转对象的键值对,值变成键,键变成值

Type Parameters

T

T extends Record<string, string | number>

Parameters

obj

T

原始对象

Returns

Record<string, string>

反转后的新对象

Example

ts
invert({ a: '1', b: '2', c: '3' })
// { '1': 'a', '2': 'b', '3': 'c' }

invert({ firstName: 'John', lastName: 'Doe' })
// { John: 'firstName', Doe: 'lastName' }

// 注意:如果有重复的值,后面的键会覆盖前面的
invert({ a: '1', b: '1' })
// { '1': 'b' }