Invert
Swap the key-value pairs of an object.
๐ฌ Usage
<script>
import {invert} from "@sveu/shared/dicts"
const obj = {"Mila": "Kunis", "Emma": "Watson", "Scarlett": "Johansson"}
invert(obj) // { Kunis: 'Mila', Watson: 'Emma', Johansson: 'Scarlett' }
</script>
๐ฉโ๐ปAPI
๐ป Arguments
Name | Description | Type | Required |
---|---|---|---|
obj | object to invert | Record<string | number | symbol, any> | yes |
โฉ๏ธ Returns
A new object with inverted key-value pairs.
๐งช Playground
Source Code ๐
Source Code
export function invert<
Key extends string | number | symbol,
Value extends string | number | symbol
>(obj: Record<string, Value>): Record<Value, Key> {
if (!obj) return {} as Record<Value, Key>
return Object.keys(obj).reduce(
(acc, key) => ({
...acc,
[obj[key]]: key,
}),
{} as Record<Value, Key>
)
}
Last update: 2023-02-14
Authors: Mohamed-Kaizen