`transposeRecords` for collections API
- Dominant language
- TypeScript
- Stars
- 3.6k
- Forks
- 681
- PR merge metrics
- No merged PRs in 30d
Description
**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.
```ts
type TablePair = { title: VNode; content: VNode }
const toTable = (elems: TablePair[]) => {
const { content, title } = transposeRecords(elems)
return (
{content}{title}
)
}
```
**Describe the solution you'd like**
[playground link](https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABFATgQzAZwA50wUwCV8I4UATTAHgGlF8APKfMSxTVGMAcwBpEAKgD4AFAChEiFCTKUAXImKkKtfsIDaAXV5iAlAqWzVgrUMQBvCYlJYoU-JhAAbOwF4LAX0RpMimSo4ULj4TTSErYDJEERsOe2VyRDhgeNlMXQsrSUiUaNi7dQBrfABPfgA3NCcQfE0klIB5ACMAKxIoADoWTgcRaQTdDMtJEcQAejHEchY4AFonLihZmG4wMnxENdnGVDRZggBbGCyRgG4+h2coItK6gH479y1dDuwQTAALEUrqjZ9BXQnDxWYGSaRQEAoJDSRwuMTAsT5ZDoLC4AiJdy7VF4Ij+SgidRWczeBQAIkicFJ-CaCgAjPwIApUDVEB4dJJiWgyU00CgqYgaYgAEwMhTAKoEVnsiwkxCknkAL35goAzKLkSy2WJNIDEQhMHAnPgOk44NwRFicDjyLogA)
```ts
export function transposeRecords(
records: Record[],
): Record {
const result = {} as Record
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
Contributor guide
Assessment
This issue has not been assessed yet.