DEV Community

Rense Bakker
Rense Bakker

Posted on • Updated on

Mapping Records to arrays

I needed this functionality to parse a configuration regardless of whether it was supplied as an array or a Record. This function converts the Record into an array of the same type:

function mapRecordToArray<T, R extends Omit<T, K>, K extends keyof T>(record: Record<string, R>, recordKeyName: K) {
  return Object.keys(record).map(key => ({ ...record[key as keyof typeof record], [recordKeyName]: key })) as T[]
}
Enter fullscreen mode Exit fullscreen mode

It can be used like this:

type Field = {
  name: string,
  label: string,
}

type Collection = {
  name: string,
  label: string,
  fields: Record<string, Omit<Field, 'name'>> | Field[]
}

const collections:Collections[] = [] // ...

collections.forEach(collection => {
  const fields = Array.isArray(collection.fields)
    ? collection.fields
    : mapRecordToArray(collection.fields, 'name')
})
// Function typings will look like this:
// function mapRecordToArray<Field, Omit<Field, "name">, "name">(record: Record<string, Omit<Field, "name">>, recordKeyName: "name"): Field[]

// Notice the return type: Field[]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)