Reputation: 1807
I'm using nodejs
and mysql
to retrieve data from database.
I need to get the result like below:
var dictionary, set_lang;
dictionary = {
"english": {
"_availablestorage": "Available Storage",
"_prayschedule": "Pray Schedule",
"_mainmenu": "Main Menu",
"_temperature": "Temperature",
"_calibration": "Calibration",
"_mosque": "Mosque"
},
"indonesia": {
"_availablestorage": "Penyimpanan Tersedia",
"_prayschedule": "Jadwal Sholat",
"_mainmenu": "Menu Utama",
"_temperature": "Suhu",
"_calibration": "Kalibrasi",
"_mosque": "Masjid"
}
};
This is my code on js file:
con.query('SELECT * FROM tbl_language;', (err, results)=>
{
//Here I do not know how to do.
//res.json(results);
});
Here is the sql fiddle.
Upvotes: 0
Views: 343
Reputation: 87
const dictionaryData = [
{ id: 0, language: 'English' },
{ id: 1, language: 'Indonesian' }
]
const languageData = [
{
language_id: 0,
key_language: '_availablestorage',
description: 'Available Storage'
},
{
language_id: 0,
key_language: '_prayschedule',
description: 'Pray Schedule'
},
{
language_id: 0,
key_language: '_mainmenu',
description: 'Main Menu'
},
{
language_id: 1,
key_language: '_availablestorage',
description: 'Tersedia'
},
{
language_id: 1,
key_language: '_prayschedule',
description: 'Jadwal'
},
{
language_id: 1,
key_language: '_mainmenu',
description: 'Menu Utama'
}
]
The response of the query is like this, then the below code will work.
const dictionary = {}
dictionaryData.forEach((data) => {
const setLang = {}
languageData.forEach((language) => {
if (data.id === language.language_id) {
setLang[language.key_language] = language.description
}
})
dictionary[data.language] = setLang
})
console.log(dictionary)
The response is:
{
English: {
_availablestorage: "Available Storage",
_mainmenu: "Main Menu",
_prayschedule: "Pray Schedule"
},
Indonesian: {
_availablestorage: "Tersedia",
_mainmenu: "Menu Utama",
_prayschedule: "Jadwal"
}
}
Now change foreach loop with your query loop. and it will work. The fiddle link is attached
Upvotes: 1