Skip to content

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