Quick Object Searches in Arrays of Objects With KeyBy in JavaScript
keyBy takes an array of object and a property name then creates an object map of that property name to the corresponding array element. This is useful to make checks for various properties in arrays easier and faster. After doing the keyBy direct property tests can be used instead of find loops or other tactics. For example:
const cars = [ { id: 'miata', hp: 155, weight: 2400 }, { id: '4c', hp: 237, weight: 2465 }, { id: 'elise', hp: 217, weight: 2000 } ]; const carIds = keyBy(cars, 'id'); console.log('Cars found (keyBy)'); console.log('miata:', 'miata' in carIds); console.log('elise:', 'elise' in carIds); console.log('ferrari:', 'ferrari' in carIds); // miata: true // elise: true // ferrari: false
The only disadvantage is that the array must be looped through once to create the key-value object:
function keyBy(arr, propertyName) { const obj = {}; for (const ele of arr) { obj[ele[propertyName]] = ele; } return obj; }
keyBy is available in utility libraries like Lodash: https://lodash.com/docs/4.17.15#keyBy
Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/keyBy.js












