A simple invert function can do this. Here is how it works:
const obj = { a: 1, b: 2, c: 3 }; console.log(invert(obj)); // { '1': 'a', '2': 'b', '3': 'c' }
This is useful when there is a list of names to ids. Sometimes you will need to check if an id exists in that list. If this is done in a loop, it is usually much faster to check an inverted id to name object that is created before the loop:
function hasIds(obj, ids) { const byId = invert(obj); return ids.map((id) => byId[id] !== undefined); } const cars = { 'miata': 1, 'elise': 2, 'elan': 3 }; console.log(hasIds(cars, [1, 2, 5])); // [ true, true, false ]
The implementation for
invert
is simple:function invert(obj) { const newObj = {}; for (const keyName in obj) { if (obj.hasOwnProperty(keyName)) { newObj[obj[keyName]] = keyName; } } return newObj; }
It is also available in many utility libraries like Lodash.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/invert.js