I'm trying to convert a JSON (a list of countries/cities in the world) to an array, and what I'm trying to do with the array is:
- Leave only the name of the countries
- Since many of the countries are repeated, only leave them once
I was able to achieve this thanks to this function (just to clarify: in the final project, fetchData
is imported from another file and the variable declaration and the array are in a document.addEventListener("DOMContentLoaded", async () => {}
, this is just one for testing purposes)
async function fetchData(url) {
const response = await fetch(url);
return await response.json();
}
(async () => {
let worldCities = await fetchData(
"https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json"
);
const countries = [...new Set(worldCities.map((item) => item.country))];
console.log(countries);
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }
With fetchData I asynchronously request a resource (the URL of the .json file), then I map an array with the file and "filter" it as I mentioned above
But the problem is that it works, but not as needed, because the output should be like this
and my output is just an array of country names
I know that I'm mapping (only) the current value required with worldCities.map((item) => item.country)
and removing repeated values with [...new Set()]
But how could I make the array returns an object like key/value pairs [country: 'country1', country: 'country2', ...]
(or something similar to the output of the image) instead of the normal array ['country1', 'country2', ...]
?
Any help is welcome, thank you very much!
CodePudding user response:
map()
it again:
const countries = [...new Set(worldCities.map((item) => item.country))].map(country => ({ country }))
Working solution:
async function fetchData(url) {
const response = await fetch(url);
return await response.json();
}
(async () => {
let worldCities = await fetchData(
"https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json"
);
const countries = [...new Set(worldCities.map((item) => item.country))].map(country => ({ country }))
console.log(countries);
})();
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
By giving it the approach below, you can achieve to get an array of unique country names. If you want an array of country objects, then you can convert the names array.
$.get('https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json', function(data) {
var res = JSON.parse(data)
var countries = res.map(function(elem){return elem.country});
const uniques = Array.from(new Set(countries));
console.log(uniques)
});