Beginner here - I'd like to create an array for my cities of the world type ahead project from a JSON file. I've fetched the data, now I would like to extract 2 key/value pairs (called name/country) and push them into a new string array that will have the syntax:
const arr = ["name, country", "name, country", "name, country"...]
Here is a sample of the data:
[]:
0: {country: "Andorra", geonameid: 3040051, name: "les Escaldes", subcountry: "Escaldes-Engordany"}
1: {country: "Andorra", geonameid: 3041563, name: "Andorra la Vella", subcountry: "Andorra la Vella"}
2: {country: "United Arab Emirates", geonameid: 290594, name: "Umm al Qaywayn", subcountry: "Umm al Qaywayn"}
3: {country: "United Arab Emirates", geonameid: 291074, name: "Ras al-Khaimah", subcountry: "Raʼs al Khaymah"}...
I know I have to use .push() and .forEach() or a for loop but I'm not sure how to go about it. Can anyone show me how?
Use map like so:
const arr = data.map(city => city.name + ", " + city.country);
arr will be a new array of the same length as data where each city object in data is mapped to the string city.name + ", " + city.country.
Demo:
const data = [ {country: "Andorra", geonameid: 3040051, name: "les Escaldes", subcountry: "Escaldes-Engordany"}, {country: "Andorra", geonameid: 3041563, name: "Andorra la Vella", subcountry: "Andorra la Vella"}, {country: "United Arab Emirates", geonameid: 290594, name: "Umm al Qaywayn", subcountry: "Umm al Qaywayn"}, {country: "United Arab Emirates", geonameid: 291074, name: "Ras al-Khaimah", subcountry: "Raʼs al Khaymah"} ];
const arr = data.map(city => city.name + ", " + city.country);
console.log(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With