@afoot/index-lookup
v0.1.1
Published
Generate an index of ids from an array of objects for quick lookup.
Downloads
3
Maintainers
Readme
Index Lookup
An ESM module for generating a lookup index from an array of object literals.
Made this specifically when working with MongoDB documents and pairing reference IDs between query results.
usage
import { indexLookup } from '@afoot/index-lookup';
const fetchResults = [
{
_id: 'abc',
name: 'Tacos',
ingredients: ['beans', 'cheese'],
},
{
_id: 'def',
name: 'Pizza',
ingredients: ['tomatoes', 'cheese'],
},
];
const lookup = indexLookup('_id', fetchResults);
console.log(lookup); // Returns ['abc','def'];
// You now have a quick lookup to find corresponding objects.
const otherResults = [
{
name: 'Tom',
favoriteFoodId: 'def'
};
]
const foodId = lookup.indexOf(otherResults[0].favoriteFood); // returns 1
const favoriteFoodName = fetchResults[foodId].name; // Returns `Pizza`