Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading