Let's dive right in:
I have a list of countries along with their respective values:
{
Mainland China: 14375,
Japan: 20,
Thailand: 19,
Singapore: 18,
South Korea: 15,
Hong Kong: 14,
Taiwan: 10,
Germany: 8,
Malaysia: 8,
Macau: 7,
France: 6,
Vietnam: 6,
Australia: 12,
United Arab Emirates: 4,
Canada: 4,
Italy: 2,
Philippines: 2,
Russia: 2,
UK: 2,
US: 8,
Cambodia: 1,
Finland: 1,
India: 1,
Nepal: 1,
Spain: 1,
Sri Lanka: 1,
Sweden: 1,
}
I want to change the keys of the object to represent each country's 2-letter code:
{
cn: "14375"
jp: "20"
th: "19"
sg: "18"
kr: "15"
sk: "14"
tw: "10"
de: "8"
my: "8"
mo: "7"
fn: "6"
vn: "6"
au: "12"
ae: "4"
ca: "4"
it: "2"
ph: "2"
ru: "2"
gb: "2"
us: "8"
ci: "1"
fi: "1"
in: "1000"
cp: "1"
es: "1"
lk: "1"
se: "1"
}
Is there a straightforward way to accomplish this? I believe using another object like the one below will be essential:
var CountryList = {
'Afghanistan': 'AF',
'Albania': 'AL',
'Algeria': 'DZ',
'American Samoa': 'AS',
...
'Zambia': 'ZM',
'Zimbabwe': 'ZW',
'Åland Islands': 'AX'
}
I have managed to make it work on a small scale, but I'm struggling to find a way to do it for each item.
Here is the screenshot from Google Chrome output: https://i.sstatic.net/SmBJe.png
Here are the steps I need to follow: 1) Retrieve data from Google Scripts 2) Convert integers to strings 3) Convert country names (keys) to their 2-digit codes.
As you can see, I have successfully completed steps 1 and 2.
Full JS File:
var countriesObj = {};
var infected_dataINT = {};
var infected_data = {};
const url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";
// Declare an async function
const getData = async () => {
// Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled
// When the variable is fetched, use the .then() callback to carry on
const DataJSON = await fetch(url).then(response =>
response.json()
)
return await DataJSON
};
console.log(getData());
getData().then(result => {
//console.log(result);
infected_dataINT = result;
console.log(infected_dataINT);
function toString(o) {
Object.keys(o).forEach(k => {
if (typeof o[k] === 'object') {
return toString(o[k]);
}
o[k] = '' + o[k];
});
return o;
}
console.log(toString(infected_dataINT));
countriesObj = toString(infected_dataINT);
// infected_data = toString(infected_dataINT);
let ObjectConversion = Object.entries(countriesObj).map(entry => [CountryList[entry[0]], entry[1]]);
infected_data = ObjectConversion;
let script = document.createElement('script');
script.src = 'js/myMapFile.js';
document.head.appendChild(script);
})
// var infected_dataINT = getData();
// var infected_data = infected_dataINT.toString();
The final output is infected_data