Typescript lage en ny Record fra en eksisterende?


Jeg prøver å mappe en Record-type til en ny i Typescript. Her er hva jeg har så langt, men det ser ut til at dette ikke er den riktige måten å lage en Record ved bruk av map på.

Noen tips?

const data: Record<string, string> = { "test": : "Test", "test2": "Test2"}
const result = Object.keys(data).map((i): Record<string, string> => [i, data[i]])

Rediger :

Her er inndataen:

const data: Record<string, CustomType> = { "Option 1": {"id": "123"}, "Option 2": {"id": "987"}}
const data_two: Record<string, CustomType> = { "Option 1": {"id": "567"}, "Option 2": {"id": "376"}}

Her er mitt forventede resultat:

En Record<string, string[] som ville se omtrent slik ut:

{ "Option 1": ["123", "567"], "Option 2": ["987", "376"] }

Svar #1

Du trenger å

(1) Implementer logikken i JavaScript først

(2) Skriv JavaScript riktig for TypeScript. Deklarer utdataobjekttypen som { [K in keyof typeof data]: string[] } og du kan få strukturen du ønsker.

type CustomType = { id: string };
const data: Record<string, CustomType> = { "Option 1": {"id": "123"}, "Option 2": {"id": "987"}}
const data_two: Record<string, CustomType> = { "Option 1": {"id": "567"}, "Option 2": {"id": "376"}}

const output: {
    [K in keyof typeof data]: string[]
} = Object.fromEntries(
    Object.keys(data).map(key => [key, []])
);
for (const obj of [data, data_two]) {
    for (const [key, customType] of Object.entries(obj)) {
        output[key].push(customType.id)
    }
}

Demo

Relaterte artikler