- Joined
- Aug 19, 2022
- Messages
- 2
- Reaction score
- 0
I have an API request and I'm generating a HTML content from its data using
The issue I'm facing is that in the array of objects I have keys that are showing content in one language or another. I need to display specific keys in mapped HTML based on the language of the page.
Example of object key:
My way of solving this isn't the DRY-est and there's some repeating code.
Please check below existing code and let me know what would be a better solution in this case. I would like to avoid generating a long HTML because of different language content in the keys. Any advices are welcomed! Thanks!
.map()
;.The issue I'm facing is that in the array of objects I have keys that are showing content in one language or another. I need to display specific keys in mapped HTML based on the language of the page.
Example of object key:
UserFromRegEN: "content in EN"
for English or UserFromRegEN: "contenu en français"
for French.My way of solving this isn't the DRY-est and there's some repeating code.
Please check below existing code and let me know what would be a better solution in this case. I would like to avoid generating a long HTML because of different language content in the keys. Any advices are welcomed! Thanks!
JavaScript:
// Find page language in URL
const findUrl = window.location.href;
const regex = /\.eu\/(\w{2})\//;
const match = regex.exec(findUrl);
const resultLangUrl = match && match[1];
let pageLang = resultLangUrl.toUpperCase();
let language = pageLang.includes("EN");
let pickContainer = document.querySelector('#container');
// deleting keys not coresponding to page language from the objects
//ex: page language is EN, delete all FR keys
if (pageLang === true) {
data.forEach(object => {
delete object['UserFromRegFR']
delete object['UserFromCityFR']
delete object['UserFromStreetFR']
});
//generate html for EN
const generateHtmlEN = data.map(test => {
return `<p>${test.UserFromRegEN}</p>
<p>${test.UserFromCityEN}</p>
<p>${test.UserFromStreetEN}</p>`
}).join('');
pickContainer.insertAdjacentHTML('afterbegin', generateHtmlEN);
} else {
data.forEach(object => {
delete object['UserFromRegEN']
delete object['UserFromCityEN']
delete object['UserFromStreetEN']
});
//generate html for FR
const generateHtmlFR = data.map(test => {
return `<p>${test.UserFromRegFR}</p>
<p>${test.UserFromCityFR}</p>
<p>${test.UserFromStreetFR}</p>`
}).join('');
pickContainer.insertAdjacentHTML('afterbegin', generateHtmlFR);
}