Skip to content

transposeRecords for collections API #3423

@scarf005

Description

@scarf005

Is your feature request related to a problem? Please describe.

While i was creating a table JSX component, I found it convenient to pass in array of title and content then to pass array of title and content. I could make a PR, however I'm not certain whether it'll have lots of use cases.

type TablePair = { title: VNode; content: VNode }

const toTable = (elems: TablePair[]) => {
  const { content, title } = transposeRecords(elems)
  return (
    <table>
      <tr>{content}</tr>
      <tr>{title}</tr>
    </table>
  )
}

Describe the solution you'd like

playground link

export function transposeRecords<K extends string, T>(
  records: Record<K, T>[],
): Record<K, T[]> {
  const result = {} as Record<string, T[]>
  for (const record of records) {
    for (const [key, value] of Object.entries(record)) {
      // deno-lint-ignore no-extra-semi
      ;(result[key] ??= []).push(value as T)
    }
  }
  return result
}

const transposed = transposeRecords([
  { a: "foo", b: 1, c: true },
  { a: "bar", b: 2, c: false },
  { a: "baz", b: 3, c: true },
])
// const transposed: Record<"a" | "b" | "c", (string | number | boolean)[]>

assertEquals(transposed, {
  a: ["foo", "bar", "baz"],
  b: [1, 2, 3],
  c: [true, false, true],
})

Describe alternatives you've considered

https://stackoverflow.com/questions/53380761/how-to-transpose-objects-in-typescript

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions