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;
}
CodePudding user response:
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,
}), {});
}