Typescript equivalent of C# ToLookup

I have a class that contains a specCode property, which is not a unique key. When I have an array of those objects, I want to convert it to a dictionary where the key is the specCode, and then the value is all the array items that have that specCode.

Right now I’m doing it manually like so:

const skusBySpecCode: { [key: string]: Sku[] } = {}

for (const sku of x.skus) {
    if (!skusBySpecCode.hasOwnProperty(sku.specCode))
        skusBySpecCode[sku.specCode] = []

Is there an easier way to do that? In C# I’d do something like this:

    .ToLookup(x => x.SpecCode)
    .ToDictionary(x => x.Key, x => x.ToArray());

>Solution :

You should probably use reduce here to reduce your array into an object. Reduce takes a generic parameter, which is the type of the accumulator. Here it should be { [key: string]: Sku[] }, but you could also use Record<string, Sku[]>.

const skusBySpecCode = skus.reduce<{ [key: string]: Sku[] }>((table, sku) => ({
    [sku.specCode]: [...(table[sku.specCode] ?? []), sku],
}), {});


Leave a Reply