Emmanuel Akinfulubi

JavaScriptBasic

Invert an object's keys and values in JavaScript

Intermediate · 3 min read

A lookup table answers one question fast. A table of plate numbers to owners tells you who owns KJA-902-XY. But what if you need the other direction: which plate belongs to Bola? You turn the table inside out, so the values become the keys and the keys become the values. This is called inverting an object.

In this tutorial you will write invert, which swaps keys and values, and see what it quietly loses when two keys share a value. Then you will write invertAll, which keeps everything by grouping. You need to know what an object is and how a for...of loop works.

Keys are unique, values are not

An object can't have the same key twice. But two keys can easily have the same value. In this table, Adaeze owns two cars:

JavaScript

const PLATE_OWNER = {
  'LSD-114-AB': 'Adaeze',
  'KJA-902-XY': 'Bola',
  'BDG-771-KM': 'Adaeze',
};

Flip it, and 'Adaeze' would have to be a key twice. It can't be. So before you write the loop, decide what should happen: keep only one plate, or keep a list of plates per owner.

Object.entries

Object.entries(obj) gives an array of [key, value] pairs, which you can walk with for...of. Writing const [key, value] in the loop head unpacks each pair into two names. This is called destructuring.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

88 Turn a lookup table inside out

fair

Invert a table of plate numbers to owners, so the owners become the keys. Two plates belong to the same owner: decide what that should do, then handle it properly.

Stuck? Three hints, smallest first
  1. 1. Walk Object.entries and assign out[value] = key.
  2. 2. Two entries with the same value collide, and the last one silently wins.
  3. 3. (out[value] ??= []).push(key) collects them instead.

Step 1: a simple invert

For each pair, store the key under the value:

Step 1

function invert(table) {
  const out = {};
  for (const [key, value] of Object.entries(table)) out[value] = key;
  return out;
}
console.log(invert({ yaba: 'Y1', ikeja: 'I2' })); // { Y1: 'yaba', I2: 'ikeja' }

out[value] = key uses square brackets, because the new key is held in a variable. With every value different, this works perfectly.

Step 2: the collision

Now try it on the plate table:

Step 2

const PLATE_OWNER = {
  'LSD-114-AB': 'Adaeze',
  'KJA-902-XY': 'Bola',
  'BDG-771-KM': 'Adaeze',
};
function invert(table) {
  const out = {};
  for (const [key, value] of Object.entries(table)) out[value] = key;
  return out;
}
console.log(invert(PLATE_OWNER)); // { Adaeze: 'BDG-771-KM', Bola: 'KJA-902-XY' }

Three plates went in, two owners came out. The loop wrote out.Adaeze = 'LSD-114-AB', then later out.Adaeze = 'BDG-771-KM', which replaced it. No error, no warning. The first plate simply vanished.

Step 3: group instead of overwrite

To keep every plate, store a list per owner. On each pair, make the list if it doesn't exist yet, then add the plate:

Step 3

const PLATE_OWNER = {
  'LSD-114-AB': 'Adaeze',
  'KJA-902-XY': 'Bola',
  'BDG-771-KM': 'Adaeze',
};
function invertAll(table) {
  const out = {};
  for (const [key, value] of Object.entries(table)) {
    (out[value] ??= []).push(key);
  }
  return out;
}
console.log(invertAll(PLATE_OWNER).Adaeze); // [ 'LSD-114-AB', 'BDG-771-KM' ]
console.log(Object.keys(invertAll(PLATE_OWNER))); // [ 'Adaeze', 'Bola' ]

The line (out[value] ??= []).push(key) packs two steps together. ??= means "assign only if the current value is null or undefined". So the first time an owner appears, out[value] becomes a new empty array. The brackets around it give back that array, whether new or existing, and .push(key) adds the plate. Written out longhand, it is:

JavaScript

const out = {};
const value = 'Adaeze';
const key = 'LSD-114-AB';
if (out[value] === undefined) out[value] = [];
out[value].push(key);
console.log(out); // { Adaeze: [ 'LSD-114-AB' ] }

Step 4: values become strings

Object keys are always strings. So when you invert a table of numbers, the numbers come back as text:

Step 4

function invert(table) {
  const out = {};
  for (const [key, value] of Object.entries(table)) out[value] = key;
  return out;
}
console.log(Object.keys(invert({ yaba: 20000 }))); // [ '20000' ]

20000 became '20000'. If you later compare it with === against a number, it won't match.

Step 5: invert twice

If inverting lost nothing, inverting twice would give back the original. Check:

Step 5

const PLATE_OWNER = {
  'LSD-114-AB': 'Adaeze',
  'KJA-902-XY': 'Bola',
  'BDG-771-KM': 'Adaeze',
};
function invert(table) {
  const out = {};
  for (const [key, value] of Object.entries(table)) out[value] = key;
  return out;
}
console.log(invert(invert(PLATE_OWNER))); // { 'BDG-771-KM': 'Adaeze', 'KJA-902-XY': 'Bola' }

LSD-114-AB is gone for good. That round trip is a quick test of whether your table is one-to-one (every value different) or many-to-one.

The full solution

The answer panel has invert and invertAll, prints both results for the plate table, and checks the collision, the grouping, the number-to-string change, the double inversion and an empty table. Press Run to see the output.

The answer

const PLATE_OWNER = {
  'LSD-114-AB': 'Adaeze',
  'KJA-902-XY': 'Bola',
  'BDG-771-KM': 'Adaeze',        // same owner as the first plate
};

function invert(table) {
  const out = {};
  for (const [key, value] of Object.entries(table)) out[value] = key;
  return out;
}

function invertAll(table) {
  const out = {};
  for (const [key, value] of Object.entries(table)) {
    (out[value] ??= []).push(key);
  }
  return out;
}

console.log(invert(PLATE_OWNER));
console.log(invertAll(PLATE_OWNER));

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the values become the keys', invert(PLATE_OWNER).Bola, 'KJA-902-XY');
test('a repeated value collides, and the last write wins', invert(PLATE_OWNER).Adaeze, 'BDG-771-KM');
test('so three plates invert to two owners', Object.keys(invert(PLATE_OWNER)).length, 2);
test('grouping keeps both of her plates', invertAll(PLATE_OWNER).Adaeze, ['LSD-114-AB', 'BDG-771-KM']);
test('with one entry per owner', Object.keys(invertAll(PLATE_OWNER)), ['Adaeze', 'Bola']);
test('a number value comes back as a string key', Object.keys(invert({ yaba: 20000 })), ['20000']);
test('so inverting twice does not return what you started with', invert(invert(PLATE_OWNER)), { 'BDG-771-KM': 'Adaeze', 'KJA-902-XY': 'Bola' });
test('an empty table inverts to an empty one', invert({}), {});

Inverting is three lines, and the interesting part is what it destroys. Object keys are unique, so any value appearing twice collapses to one entry and the earlier plate vanishes with no error. The double inversion assertion shows the damage: LSD-114-AB is simply gone.

(out[value] ??= []).push(key) is the fix and the idiom worth learning — logical assignment creates the array only when the key is missing, then the expression evaluates to the array so push follows on the same line. The other quiet conversion is that values become keys, and keys are strings: invert a table of numbers and 20000 comes back as '20000'. A one-to-one table can be inverted; a many-to-one table has to be grouped, and you should know which one you have before you write the loop.

Common mistakes

  • Inverting a many-to-one table with plain assignment. Repeated values overwrite each other with no error. Group them into arrays.
  • Writing out.value = key. That makes a key literally called "value". Use out[value].
  • Forgetting that keys are strings. Inverted numbers come back as text, so === against a number fails.

Try it yourself

  1. Write isOneToOne(table) that is true when no two keys share a value. (Hint: compare the number of keys before and after invert.)
  2. Invert { yaba: 20000, ikeja: 35000 } and turn the keys back into numbers with Number.
  3. Rewrite invertAll with Object.entries(table).reduce(...) instead of a loop.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.