DEV Community

Rense Bakker
Rense Bakker

Posted on • Edited on

1

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

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay