1.38.0invert
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
objectTrequiredThe 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
Basic usage
const roles = {
admin: "administrator",
user: "member",
};
invert(roles);
// {
// administrator: "admin",
// member: "user",
// }Numeric values
const status = {
pending: 1,
success: 2,
failed: 3,
};
invert(status);
// {
// "1": "pending",
// "2": "success",
// "3": "failed",
// }Boolean values
const flags = {
enabled: true,
disabled: false,
};
invert(flags);
// {
// "true": "enabled",
// "false": "disabled",
// }Duplicate values
const roles = {
admin: "user",
member: "user",
};
invert(roles);
// {
// user: "member",
// }Values are converted to strings
const data = {
first: 10,
second: 20,
};
invert(data);
// {
// "10": "first",
// "20": "second",
// }Empty object
invert({});
// {}Original object is unchanged
const data = {
first: "one",
second: "two",
};
const result = invert(data);
console.log(data);
// {
// first: "one",
// second: "two",
// }