I am trying to create a map of COVID hotspots across the US. The array of objects I am getting from an API does not include lat and lng positioning so I created my own array to pass these values into the returned array with a .then statement. The issue that I am having is that the array that I created is not allowing me to run a .forEach function on it and push the values to a new (third) array. Below is my code and a small sample of each of the arrays. I got the Lat / Lng info from here https://inkplant.com/code/us-state-mysql-table.
My Array:
let StateLatLng = [
{state: "Alabama", lat: 32.806671, lng: -86.791130},
{state: "Alaska", lat: 61.370716, lng: -152.404419},
{state: "Arizona", lat: 33.729759, lng: -111.431221},
{state: "Arkansas", lat: 34.969704, lng: -92.373123},
etc... ]
Array returned from API:
0: Object { state: "California", updated: 1603065757213, cases: 875557, … }
1: Object { state: "Texas", updated: 1603065757213, cases: 870156, … }
2: Object { state: "Florida", updated: 1603065757213, cases: 755020, … }
3: Object { state: "New York", updated: 1603065757213, cases: 519994, … }
My Code:
.then((result) => {
let data = new Set(result.map((item) => item.state));
StateLatLng.forEach((item) data.has(item.state) && (item.lat = test);
console.log(data);
})
I am attempting to use the shared state name for both arrays to find the matching object and then push the data onto the new array called data for use later. Since I created the first array I am not sure if I should format it differently t make the job easier or if I should use the MySQL table that is linked in the URL that I got the lat/lng from. I opted not to use the SQL table because I am unfamiliar with that data type.
It can be a one-liner
The key observation is that you are ALWAYS looking up the state in your self-made array. So why not make it an object, with the state as the key? You made it yourself, so you are free to do so.
This means you don't have to "manually" search for the state in your array. If you have a state name, you can just tell Javascript to look at that state's data.
You can simply use
results.map
to convert the originalstateResult
into a new object that consist of the original stateResult plus the relevant element of your self-made LatLng object, using:({...StateLatLng[stateResult.state],...stateResult})
The result is as follows: