Invert Records With Entries And FromEntries
Inverting a record with Object.entries and fromEntries gives reverse lookups, but duplicate values collide silently unless the inverse collects lists.
Code
// Invert a lookup table: keys become values, values become keys
const slugToName = {
'auth-service': 'Auth Service',
'billing-api': 'Billing API',
'web-app': 'Web App',
};
const nameToSlug = Object.fromEntries(
Object.entries(slugToName).map(([slug, name]) => [name, slug]),
);
console.log(nameToSlug['Billing API']); // billing-api
console.log('web-app' in slugToName && 'Web App' in nameToSlug);
// Duplicate values collide: with plain inversion the last one wins silently
const ownerToPet = { ana: 'cat', bo: 'cat', cy: 'dog' };
const petToOwner = Object.fromEntries(
Object.entries(ownerToPet).map(([owner, pet]) => [pet, owner]),
);
console.log(petToOwner.cat); // 'bo' - ana was overwritten!
// Collision-safe variant: collect owners into arrays instead
const petToOwners = {};
for (const [owner, pet] of Object.entries(ownerToPet)) {
(petToOwners[pet] ??= []).push(owner);
}
console.log(petToOwners.cat, petToOwners.dog); // [ 'ana', 'bo' ] [ 'cy' ]Output
Captured from a sandboxed run of this snippet in the build pipeline.
billing-api
true
bo
[ 'ana', 'bo' ] [ 'cy' ]What the demo inverts
Object.entries(slugToName).map(…) swaps each pair and Object.fromEntries rebuilds it, so nameToSlug[“Billing API”] prints billing-api and the membership check across both directions prints true.
Duplicate values are where plain inversion breaks: two owners share cat, and petToOwner.cat prints bo, with ana overwritten without any error. The collision-safe variant collects into arrays with (petToOwners[pet] ??= []).push(owner), printing both owners for cat.
Points worth noting
- fromEntries keeps the last pair for duplicate keys, silently.
- ??= seeds the array once, then push appends every owner.
Interactive Tools for This Topic
FAQ
- How do you invert when values repeat?
- Collect into arrays: the demo builds petToOwners where cat maps to both ana and bo, instead of a plain fromEntries inversion that silently keeps only the last owner.
Report a problem with this exampleOpens a pre-filled issue on GitHub.