Given:
TupleType
: a tuple of similar objectsKeyProperty
: a key that is...
string
valuesProvide:
A Record
-like object that indexes the tuple entries using the specified key property instead of array indexes.
Type:
type RecordOf<
TupleType extends Array<object> | ReadonlyArray<object>,
KeyProperty extends keyof TupleType[number]
> = {
[Item in TupleType[number] as `${Item[KeyProperty]}`]: Item;
};
Transformation function:
function toRecord<
TupleType extends Array<object> | ReadonlyArray<object>,
KeyProperty extends keyof TupleType[number]
>(
tuple: TupleType,
keyProperty: KeyProperty
): RecordOf<TupleType, KeyProperty> {
return Object.fromEntries(
tuple.map((item: TupleType[number]) => [String(item[keyProperty]), item])
) as RecordOf<TupleType, KeyProperty>;
}
const animalList = [
{ name: 'Shadow', species: 'dog', breed: 'Golden Retriever' },
{ name: 'Chance', species: 'dog', breed: 'Bulldog' },
{ name: 'Sassy', species: 'cat', breed: 'Siamese' },
{ name: 'Jake the Dog', species: 'dog', breed: 'Bulldog', isMagical: true },
] as const;
const animals = toRecord(animalList, 'name');
console.log(animals.Shadow);
console.log(animals['Jake the Dog'].isMagical);
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too