I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language.
Although I believe this should be a simple task, I seem to be struggling to find the solution.
The object structure I am working with is as follows:
{
section1: {
btn: { en: "English", es: "Español" },
title: {
en: "Web Frontend Developer",
es: "Desarrollador Web de Frontend"
},
card: {
title: { en: "Hello!", es: "Hola!" },
btn: { en: "Get started", es: "Empecemos" },
}
}
}
To achieve this, I need to pass this object as the first parameter to a function, and the second parameter should specify the language (e.g., "en" or "es"). The function call should look something like this:
filterObjByLanguage(obj, "es")
The expected output would be:
{
section1: {
btn: "Español",
title: "Desarrollador Web de Frontend",
card: {
title: "Hola!",
btn: "Empecemos"
}
}
}
In essence, the function should iterate through each part of the object and select the appropriate text based on the specified language key (
{ en:"text", es: "texto" }
).
I have made an attempt at this, but currently, only the first layer of the object is returned correctly while the rest remains undefined.
const filterObjByLanguage= (obj: any, lang: string): any => {
const output = Object.assign(obj, {});
const loop = (obj: any, isRoot: boolean = true): any => {
for (var k in obj) {
const value = output[k];
const valueAtSelected = value?.[lang];
if (typeof value === "string") {
continue;
} else if (valueAtSelected) {
if (isRoot) output[k] = valueAtSelected;
else return valueAtSelected;
} else {
if (isRoot) output[k] = loop(value, false);
else return loop(value, false);
}
}
};
loop(output);
return output;
};