File size: 1,532 Bytes
53f091c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
type NestedObject = {
[key: string]: string | NestedObject;
};
type FlattenedObject = {
[key: string]: string;
};
export function flattenObject(
obj: NestedObject,
parentKey: string = '',
): FlattenedObject {
const result: FlattenedObject = {};
for (const [key, value] of Object.entries(obj)) {
const newKey = parentKey ? `${parentKey}.${key}` : key;
if (typeof value === 'object' && value !== null) {
Object.assign(result, flattenObject(value as NestedObject, newKey));
} else {
result[newKey] = value as string;
}
}
return result;
}
type TranslationTableRow = {
key: string;
[language: string]: string;
};
/**
* Creates a translation table from multiple flattened language objects.
* @param langs - A list of flattened language objects.
* @param langKeys - A list of language identifiers (e.g., 'English', 'Vietnamese').
* @returns An array representing the translation table.
*/
export function createTranslationTable(
langs: FlattenedObject[],
langKeys: string[],
): TranslationTableRow[] {
const keys = new Set<string>();
// Collect all unique keys from the language objects
langs.forEach((lang) => {
Object.keys(lang).forEach((key) => keys.add(key));
});
// Build the table
return Array.from(keys).map((key) => {
const row: TranslationTableRow = { key };
langs.forEach((lang, index) => {
const langKey = langKeys[index];
row[langKey] = lang[key] || ''; // Use empty string if key is missing
});
return row;
});
}
|