Invert keys and values of an object
Swap every key with its value.
function invert(object) { return Object.fromEntries(Object.entries(object).map(([key, value]) => [value, key])); }
Input & expected output
Input
{
"delivered": "250",
"deferred": "451"
}Expected output
{
"250": "delivered",
"451": "deferred"
}The edge case
Input
{
"a": "x",
"b": "x"
}Expected output
{
"x": "b"
}Know the limits
- Values become string keys; duplicates keep the last key, as the edge case shows.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Invert keys and values of an object from the original 1loc collection by Nguyen Huu Phuoc, with johandalabacka. Copyright (c) 2020 phuoc-ng. MIT licensed.
Keeps the Object.fromEntries variant. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Pick properties from an object — Build a new object with only the requested own properties.
- Omit properties from an object — Keep the own enumerable fields that are not in a supplied list.
- Create an object from pairs of key and value — Turn [key, value] pairs into a plain object with Object.fromEntries.