Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

pick and omit utilities for objects in JavaScript

94 pick, omit, pickBy and invert

easy

Build four object utilities out of Object.entries and Object.fromEntries: pick a list of keys, omit a list of keys, pickBy a predicate over the values, and invert to swap keys with values. Show that a rest destructure is omit with the keys written by hand, and find the two things invert does to your data.

Stuck? Three hints, smallest first
  1. 1. Object.entries gives [key, value] pairs, Object.fromEntries takes them back. Everything here is a filter or a map between the two.
  2. 2. For pick, map over the keys you were given, not over the object, so the result comes out in the order you asked for.
  3. 3. A key that is not in the object should not appear in the result at all, which is a filter before the map, not an undefined after it.

The answer

const pick = (source, keys) =>
  Object.fromEntries(keys.filter((k) => k in source).map((k) => [k, source[k]]));

const omit = (source, keys) =>
  Object.fromEntries(Object.entries(source).filter(([k]) => !keys.includes(k)));

const pickBy = (source, keep) =>
  Object.fromEntries(Object.entries(source).filter(([k, v]) => keep(v, k)));

const invert = (source) =>
  Object.fromEntries(Object.entries(source).map(([k, v]) => [v, k]));

const account = { id: 'AC-9', name: 'Bisi Adeyemi', bank: 'GTBank', balance: 48500, pin: '1234', otp: null };

const publicView = pick(account, ['name', 'bank']);
const withAbsentKey = pick(account, ['name', 'nin']);
const withoutSecrets = omit(account, ['pin', 'otp']);
const keysStillThere = Object.keys(account).length;
const filled = pickBy(account, (value) => value !== null);

const { pin, otp, ...rest } = account;
const restMatchesOmit = same(rest, withoutSecrets);

const zones = invert({ lekki: 'zone-a', ikeja: 'zone-b' });
const collapsed = invert({ ada: 'north', obi: 'north' });
const numbered = invert({ lekki: 1, ikeja: 2 });
const roundTrip = invert(numbered);

console.log('pick   :', publicView, '| absent key:', Object.keys(withAbsentKey));
console.log('omit   :', withoutSecrets, '| original keys:', keysStillThere);
console.log('invert :', zones, '| duplicates:', collapsed);
console.log('numbers:', numbered, '| back again:', roundTrip);

Output


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

9 checks

test('pick keeps the listed keys, in the order they were listed', publicView, { name: 'Bisi Adeyemi', bank: 'GTBank' });
test('a key that is not there is left out, not set to undefined', Object.keys(withAbsentKey), ['name']);
test('omit is the complement, and keeps the source order', Object.keys(withoutSecrets), ['id', 'name', 'bank', 'balance']);
test('neither one touches the original', keysStillThere, 6);
test('a rest destructure is omit with the keys written out', [restMatchesOmit, pin, otp], [true, '1234', null]);
test('pickBy filters on the value', Object.keys(filled), ['id', 'name', 'bank', 'balance', 'pin']);
test('invert swaps the pairs', zones, { 'zone-a': 'lekki', 'zone-b': 'ikeja' });
test('two keys sharing a value collapse to one, and the last write wins', collapsed, { north: 'obi' });
test('and every inverted key is a string, so a number does not survive the trip', [Object.keys(numbered), roundTrip.lekki, typeof roundTrip.lekki], [['1', '2'], '1', 'string']);

Object.entries and Object.fromEntries turn an object into a list and back, which means the whole vocabulary of array methods becomes available for objects. That is the point of this exercise more than the four functions: once you see the round trip, mapValues, mapKeys, filterKeys and the rest are one line each.

Prefer the rest destructure when the keys are known at authoring time — const { pin, ...rest } = account is clearer than any helper and needs no import. Reach for omit when the list of keys is a variable.

invert is the one with teeth. Object keys are strings, so every value becomes a string on the way in: invert twice and the number 1 comes back as '1'. And keys are unique, so two entries sharing a value collapse into one, last write winning, with no error. If either matters, invert into a Map instead, which keeps the key type, or into a Map of arrays, which keeps them all.

One more trap not asserted above: pick uses in, which sees inherited properties, so pick(account, ['toString']) happily returns a function. Swap in for Object.hasOwn if the key list is not trusted.

Newsletter

New writing, when it lands.

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