How To Cast An Array Of Objects Into A Dictionary Object in Typescript

Mitchell Garcia
Front-End Society
Published in
2 min readJan 9, 2018

A common pattern in in Javascript is to cast arrays of objects into a separate object, with a certain property defined as the new object’s key.

For example, instead of [{id: 'abfq-f39f', name: ‘Test’}], you would have {‘abfq-f39f’: {id: 1, name: 'Test'}}

Why is it common? Because it makes accessing the object you really want easier. This data type is usually called a dictionary.

One benefit of casting your arrays to dictionaries is that you’ll never have to write methods to find objects by ID again. You will simply access them by their ID directly. For example, instead of writing a method called getById(objectName, id), you would just access it like any prop on the object like this: objectName[id].

This tiny utility method (written in Typescript!) provides you with a type-safe dictionary for your reading pleasure.

function normalizeArray<T>(array: Array<T>, indexKey: keyof T) {
const normalizedObject: any = {}
for (let i = 0; i < array.length; i++) {
const key = array[i][indexKey]
normalizedObject[key] = array[i]
}
return normalizedObject as { [key: string]: T }
}

to circle it back to our previous example:

const test = normalizeArray([{id: 'abfq-f39f', name: ‘Test’}], 'id')console.log(test)
// {‘abfq-f39f’: {id: 1, name: 'Test'}}

much cleaner, right?

View Gist

Thank you for reading the Front-End Society Blog! Hop on this train early & bookmark our site. Additionally, you can follow me on Twitter.

--

--