First of all, i've read similar posts like this (here) but couldn't make it work somehow(:/), maybe i'm missing something. This is why i'm here. Basically i have a language translation file, and a json data that needs to be translated depend on the lang file. And this json data has nested objects which i need to iterate. Here are the file, data and code i have;
Translation file;
[
{
"Women": "Kadın"
},
{
"What's New": "Yeni Çıkanlar"
},
{
"Tops": "Üstler"
}
]
Json data(i need to translate name values if there is a match in file);
{
"id": 2,
"parent_id": 1,
"name": "Default Category",
"is_active": true,
"position": 1,
"level": 1,
"product_count": 2072,
"children_data": [
{
"id": 20,
"parent_id": 2,
"name": "Women",
"is_active": true,
"position": 3,
"level": 2,
"product_count": 1012,
"children_data": [
{
"id": 21,
"parent_id": 20,
"name": "Tops",
"is_active": true,
"position": 1,
"level": 3,
"product_count": 784,
"children_data": [
{
"id": 23,
"parent_id": 21,
"name": "Jackets",
"is_active": true,
"position": 1,
"level": 4,
"product_count": 186,
"children_data": []
},
{
"id": 24,
"parent_id": 21,
"name": "Hoodies & Sweatshirts",
"is_active": true,
"position": 2,
"level": 4,
"product_count": 182,
"children_data": []
},
{
"id": 25,
"parent_id": 21,
"name": "Tees",
"is_active": true,
"position": 3,
"level": 4,
"product_count": 192,
"children_data": []
}
]
}
]
}
]}
What I Did;
I created reqursive function that would map the object given for every key in the translation file, and iterate in every nested object in the nested data. But when i run it, looks like it goes infinitive loop and i dont get stack overflow, just keeps running(tryed to console log it just logs object constantly). I tryed to understand what's happening but depends on other posts it looks just fine. Somehow i couldn't iterate every children_data
object in the data. So here is my code, and could really use some help. Thank you.
function reqursiveTranslate(langCode, p_object) {
//i send the whole data to this func in the first place and expect to get translated data
var categories = require('./lang/categories/' + langCode + '.json'); //the file
categories.forEach((cat) => {
Object.entries(cat).map(([key, value]) => {
if (p_object.name === key) {
p_object.name = value //change the name with lang key
}
Object.keys(p_object).forEach(k => {
if (typeof p_object[k] === 'object' && Object.keys(p_object[k]).length > 0) {
//console.log('here');
//console.log(p_object[k]);
p_object[k] = reqursiveTranslate(langCode, p_object[k]);
}
})
})
});
return p_object;
}
EDIT: With the help of @halilcakar found out above code works practically, but my problem is i get the data from another rest api and when it comes bigger i face with performance issues, take so long to get the translated data. So maybe a possible better approach on this would be usefull in order to reduce the cost of the reqursive function with bigger data.