Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Record from Array in TS

I have an array, and I want to make a Record from this data. I have sth written but it doesn't work. Main problem is how to iterate my array with saving Record.

function createTypesWithTranslationsRecords(types: { header: string; translation: string }[]) : Record<string, string> {
  const locationTypesMap : Record<string, string> = types.forEach((type) => {type.header: type.translation});
  return locationTypesMap;
}
like image 649
HappyProgrammer Avatar asked Feb 12 '26 11:02

HappyProgrammer


1 Answers

Like this:

function createTypesWithTranslationsRecords(types: { header: string; translation: string }[]): Record<string, string> {
    const locationTypesMap: Record<string, string> = {};
    types.forEach((type) => {
        locationTypesMap[type.header] = type.translation;
    });
    return locationTypesMap;
}

Or use 'reduce':

function createTypesWithTranslationsRecords(types: { header: string; translation: string }[]): Record<string, string> {
    return types.reduce((pre, type) => ({
        ...pre,
        [type.header]: type.translation,
    }), {});
}
like image 177
lrwlf Avatar answered Feb 15 '26 01:02

lrwlf