Home > other >  Typescript equivalent of C# ToLookup
Typescript equivalent of C# ToLookup

Time:11-08

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] = []
    
    skusBySpecCode[sku.specCode].push(sku)
}

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

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

CodePudding user response:

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) => ({
    ...table,
    [sku.specCode]: [...(table[sku.specCode] ?? []), sku],
}), {});

Playground

  • Related