Swap the keys and values of an object in JavaScript
Intermediate · 3 min read
Lookup tables often need to work both ways. If you have city names mapped to airport codes, { lagos: 'LOS' }, you will soon want the reverse: given 'LOS', which city is it? Swapping the keys and values gives you that reverse table without typing it twice.
In this tutorial you will write invert, which turns { lagos: 'LOS', abuja: 'ABV', kano: 'KAN' } into { LOS: 'lagos', ABV: 'abuja', KAN: 'kano' }. Then you will find the two ways the simple version quietly loses data, and write a version that doesn't. You need to know objects, arrays and map.
Entries, flipped
Object.entries turns an object into [key, value] pairs, and Object.fromEntries turns pairs back into an object:
console.log(Object.entries({ lagos: 'LOS' })); // [ [ 'lagos', 'LOS' ] ]
console.log(Object.fromEntries([['LOS', 'lagos']])); // { LOS: 'lagos' }
So if you flip every pair in the middle, the keys and values swap places.
Object keys are always text
One rule matters a lot in this exercise: a plain object's keys are always strings (or symbols). If you use a number as a key, it is turned into text:
const table = {};
table[1] = 'one';
console.log(Object.keys(table)); // [ '1' ]
Here is the exercise. Try it yourself first if you like, then read on and we will build it.
16 Swap the keys and values
fairReturn a copy where each value becomes a key and each key becomes a value. Then work out what happens when two keys share a value.
Stuck? Three hints, smallest first
- 1. Map over the entries, reversing each pair, then rebuild the object.
- 2. Object keys are always strings, so a numeric value becomes a string key.
- 3. If two keys hold the same value, one of them has to lose.
Step 1: flip one pair
Destructuring unpacks a pair into two names, and you can build the new pair in the other order:
const flip = ([k, v]) => [v, k];
console.log(flip(['lagos', 'LOS'])); // [ 'LOS', 'lagos' ]
Step 2: flip them all
Put the three pieces together: object to pairs, flip each pair, pairs to object:
const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
const codes = { lagos: 'LOS', abuja: 'ABV', kano: 'KAN' };
console.log(invert(codes)); // { LOS: 'lagos', ABV: 'abuja', KAN: 'kano' }
console.log(invert(invert(codes))); // { lagos: 'LOS', abuja: 'ABV', kano: 'KAN' }
console.log(codes); // { lagos: 'LOS', abuja: 'ABV', kano: 'KAN' }
Inverting twice gets you back where you started, and the original codes is untouched, because invert builds a new object.
Step 3: the first trap, shared values
What if two keys hold the same value? Ojota and Yaba are both in Lagos:
const collides = { ojota: 'lagos', yaba: 'lagos', wuse: 'abuja' };
console.log(invert(collides)); // { lagos: 'yaba', abuja: 'wuse' }
Three keys went in, two came out. An object can only have one lagos key, so when the second pair arrives it overwrites the first. ojota is gone, and nothing warns you.
Step 4: keep every key in a list
To keep everything, store a list of keys under each value instead of a single key:
const invertToLists = (obj) => {
const out = {};
for (const [k, v] of Object.entries(obj)) (out[v] ??= []).push(k);
return out;
};
console.log(invertToLists(collides)); // { lagos: [ 'ojota', 'yaba' ], abuja: [ 'wuse' ] }
??= means "assign only if it is currently null or undefined". The first time a value is seen, out[v] ??= [] creates an empty list. After that it leaves the existing list alone. Either way the expression gives you the list, and push(k) adds the key to it.
Step 5: the second trap, numbers become strings
const numeric = { a: 1, b: 2 };
console.log(invert(numeric)); // { '1': 'a', '2': 'b' }
console.log(typeof Object.keys(invert(numeric))[0]); // string
console.log(Object.keys(invert({ a: 1, b: '1' })).length); // 1
The number 1 became the key '1'. That means the number 1 and the string '1' end up as the same key, so { a: 1, b: '1' } collapses to one entry.
Step 6: objects as values
An object value is worse. Used as a key, any plain object turns into the same text:
console.log(Object.keys(invert({ a: { x: 1 } }))); // [ '[object Object]' ]
Every object value would land on that one key. If your values aren't strings or numbers, invert into a Map instead, because a Map keeps keys of any type apart:
console.log(new Map([[{ x: 1 }, 'a'], [{ x: 1 }, 'b']]).size); // 2
The two { x: 1 } objects look alike, but they are different objects, so the Map keeps both.
The full solution
The panel inverts the airport codes, inverts them back, then shows the shared-value case with both versions and the number-to-string case. Press Run to see each one.
const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
// Keeping every key that shared a value, rather than losing all but one.
const invertToLists = (obj) => {
const out = {};
for (const [k, v] of Object.entries(obj)) (out[v] ??= []).push(k);
return out;
};
const codes = { lagos: 'LOS', abuja: 'ABV', kano: 'KAN' };
const collides = { ojota: 'lagos', yaba: 'lagos', wuse: 'abuja' };
const numeric = { a: 1, b: 2 };
console.log('codes inverted :', invert(codes));
console.log('twice gets back :', invert(invert(codes)));
console.log('--- values that collide ---');
console.log('naive invert :', invert(collides), '<- ojota is gone');
console.log('grouped invert :', invertToLists(collides));
console.log('--- values that were not strings ---');
console.log('numeric inverted :', invert(numeric));
console.log('key types :', Object.keys(invert(numeric)).map((k) => typeof k), '<- 1 became "1"');
Output
13 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 13 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('keys and values swap', invert(codes), { LOS: 'lagos', ABV: 'abuja', KAN: 'kano' });
test('inverting twice returns the original', invert(invert(codes)), codes);
test('an empty object inverts to an empty object', invert({}), {});
test('a single pair', invert({ a: 'b' }), { b: 'a' });
test('the original is not modified', codes, { lagos: 'LOS', abuja: 'ABV', kano: 'KAN' });
test('a colliding value keeps only the last key', invert(collides), { lagos: 'yaba', abuja: 'wuse' });
test('so the result is smaller than the input', Object.keys(invert(collides)).length, 2);
test('while the grouped version keeps both', invertToLists(collides), { lagos: ['ojota', 'yaba'], abuja: ['wuse'] });
test('numeric values become string keys', Object.keys(invert(numeric)), ['1', '2']);
test('and they really are strings', typeof Object.keys(invert(numeric))[0], 'string');
test('so 1 and "1" collide after inverting', Object.keys(invert({ a: 1, b: '1' })).length, 1);
test('an object value stringifies badly', Object.keys(invert({ a: { x: 1 } })), ['[object Object]']);
test('which is why a Map is better for non-string keys', new Map([[{ x: 1 }, 'a'], [{ x: 1 }, 'b']]).size, 2);
The one-liner works, and it loses data in two ways worth knowing about. Colliding values silently drop all but the last key — the assertion shows a three-key object becoming a two-key one, with ojota gone. And every object key is a string, so the numeric value 1 becomes the key '1', which means { a: 1, b: '1' } inverts to a single entry.
An object value is worse still: it stringifies to '[object Object]', so every object value collapses into one key. If your values are not strings or numbers, invert into a Map, which keeps keys of any type distinct.
Common mistakes
- Assuming every value is unique. Shared values silently drop keys. Use the list version when they can repeat.
- Expecting number keys to stay numbers. Object keys are strings, so
1comes back as'1'. - Inverting objects with object values. They all become
'[object Object]'. Use aMap.
Try it yourself
- Write
hasUniqueValues(obj)that returnstrueonly when no two keys share a value. (Hint: compare sizes.) - Invert
{ a: 1, b: 2 }and turn the keys back into numbers withNumber. - Write
invertToMap(obj)that returns aMapfrom each value to its key.