Utility function for inverting key/value pairs of JavaScript objects
npx @tessl/cli install tessl/npm-invert-kv@4.2.0Invert KV is a utility function for inverting the key/value pairs of JavaScript objects. It transforms object keys into values and values into keys, supporting both regular properties and symbol properties with robust error handling.
npm install invert-kvimport invertKeyValue from "invert-kv";The package is ES module only (no CommonJS support).
import invertKeyValue from "invert-kv";
// Basic object inversion
invertKeyValue({foo: 'bar', hello: 'world'});
//=> {bar: 'foo', world: 'hello'}
// Handles string and number keys
invertKeyValue({foo: 'bar', 1: 'one'});
//=> {bar: 'foo', one: '1'}
// Supports symbols
const sym = Symbol('test');
invertKeyValue({foo: sym, unicorn: 'rainbow'});
//=> {[sym]: 'foo', rainbow: 'unicorn'}Inverts the key/value pairs of an object, creating a new object where the original keys become values and the original values become keys.
/**
* Invert the key/value of an object
* @param object - The object to invert (must be non-null object)
* @returns A new object with inverted key/value pairs
* @throws TypeError if input is not an object or is null
*/
function invertKeyValue<T extends Record<PropertyKey, PropertyKey>>(
object: T
): {[P in keyof T as T[P]]: keyof T extends number ? Exclude<keyof T, number> | string : P};The function:
TypeError with message "Expected an object" for invalid inputs (null, undefined, or non-objects)Usage Examples:
import invertKeyValue from "invert-kv";
// String properties
invertKeyValue({foo: 'bar', '๐ฆ': '๐'});
//=> {bar: 'foo', '๐': '๐ฆ'}
// Mixed string and number properties
invertKeyValue({name: 'Alice', 1: 'first', 2: 'second'});
//=> {Alice: 'name', first: '1', second: '2'}
// Symbol properties
const mySymbol = Symbol('myKey');
invertKeyValue({regularKey: mySymbol, anotherKey: 'value'});
//=> {[mySymbol]: 'regularKey', value: 'anotherKey'}
// Symbols as keys
const keySymbol = Symbol('keySymbol');
invertKeyValue({[keySymbol]: 'symbolValue', normalKey: 'normalValue'});
//=> {symbolValue: keySymbol, normalValue: 'normalKey'}
// Error handling
try {
invertKeyValue(null);
} catch (error) {
console.log(error.message); // "Expected an object"
}
try {
invertKeyValue("not an object");
} catch (error) {
console.log(error.message); // "Expected an object"
}/**
* Generic type-safe version with mapped types
*/
function invertKeyValue<T extends Record<PropertyKey, PropertyKey>>(
object: T
): {[P in keyof T as T[P]]: keyof T extends number ? Exclude<keyof T, number> | string : P};The TypeScript definition provides:
T extends Record<PropertyKey, PropertyKey> ensuring both keys and values are valid PropertyKey types