CyrefJS
CCyrefJS
فا
Back to documentation
Object/Since 1.38.0

invert

Creates a new object by using the original object's values as keys and its keys as values.

invert(object):Record<string, keyof T>

How it works

The function iterates over the object's own enumerable string-keyed properties. For each property, its value is converted to a string and used as a key in the resulting object, while the original key becomes the value.

Duplicate values

If multiple properties have the same value after string conversion, the later property overwrites the earlier one because the result uses a single key for that value.

Enumerable properties

The implementation uses Object.keys, so only the object's own enumerable string-keyed properties are included. Inherited and symbol-keyed properties are ignored.

Parameters

objectTrequired

The object whose keys and values should be inverted.

Returns

Record<string, keyof T>

A new object whose stringified values from the original object are keys and whose original keys are values.

Examples

01

Basic usage

TypeScript
const roles = {
  admin: "administrator",
  user: "member",
};

invert(roles);
// {
//   administrator: "admin",
//   member: "user",
// }
02

Numeric values

TypeScript
const status = {
  pending: 1,
  success: 2,
  failed: 3,
};

invert(status);
// {
//   "1": "pending",
//   "2": "success",
//   "3": "failed",
// }
03

Boolean values

TypeScript
const flags = {
  enabled: true,
  disabled: false,
};

invert(flags);
// {
//   "true": "enabled",
//   "false": "disabled",
// }
04

Duplicate values

TypeScript
const roles = {
  admin: "user",
  member: "user",
};

invert(roles);
// {
//   user: "member",
// }
05

Values are converted to strings

TypeScript
const data = {
  first: 10,
  second: 20,
};

invert(data);
// {
//   "10": "first",
//   "20": "second",
// }
06

Empty object

TypeScript
invert({});
// {}
07

Original object is unchanged

TypeScript
const data = {
  first: "one",
  second: "two",
};

const result = invert(data);

console.log(data);
// {
//   first: "one",
//   second: "two",
// }
Built with@cyref/js·Official documentation