I've got 2 arrays - countryNames and countryCodes. The index sequence of items inside those arrays align as they come from the same API, i.e. countryNames[0] is Afghanistan and countryCodes[0] is "AF" etc.
I am trying to create a new, seperate object to store the data in key/value pairs neatly (like JSON object does) but I had no success yet. Somebody suggested to loop through them but I'm not too sure how to do that. Any help would be much appreciated!
Below is the only code that I had some kind of success with. It gives me an object (albeit weird looking one) but it doesn't store the data in key / value pair relationship.
var keys = [];
var values = [];
fetch("https://restcountries.eu/rest/v2/all")
.then((response) => {
return response.json();
})
.then((data) => {
const codes = data.map(item => item.alpha2Code);
values.push(codes);
const names = data.map(item => item.name);
keys.push(names);
var result = [];
keys.forEach((key, i) => result[key] = values[i]);
console.log(result);
});
I just want to have something like -
{
CountryName: CountryCode,
2ndCountryName: 2ndCountryCode,
3rdCounryName: 3rdCountryCode,
etc.....
};