Reputation: 81
I have a table that has country, state, city, latitude/longitude of the city. I am trying to build a json string as show below.
{
"country": "usa",
"states": [
{
"name": "Alabama",
"state_code": "AL",
"cities": [
{
"name": "Abbeville",
"latitude": "31.57184000",
"longitude": "-85.25049000"
},
{
"name": "Adamsville",
"latitude": "33.60094000",
"longitude": "-86.95611000"
}
]
},
{
"name": "Alaska",
"state_code": "AK",
"cities": [
{
"name": "Akutan",
"latitude": "54.13350000",
"longitude": "-165.77686000"
},
{
"name": "Aleutians East Borough",
"latitude": "54.85000000",
"longitude": "-163.41667000"
}
]
}
]
}
The database query results are in a array: jsonData. I have the code that put's the country. Not sure how to add a state if it doesn't exist and a city if it doesn't exist with the cities latitude and longitude (the portion where I have ???)
let jsonData1 = [];
for (let item of jsonData) {
if(countryExists(jsonData1, item['COUNTRY'])) {
??
}
else {
jsonData1.push({ country: item['COUNTRY']});
}
}
function countryExists (JSON, country) {
var hasMatch = false;
for (var index = 0; index < JSON.length; ++index) {
var item = JSON[index];
if(item.country === country) {
hasMatch = true;
break;
}
}
return hasMatch;
}
Upvotes: 0
Views: 1118
Reputation: 809
Assuming you want to stick with the schema you choose, you could when you adding a country with no states, set the value of the state's name to a default e.g. none
, you could also do the same for the latitude
and longitude
.
However, I would recommend reconsidering the schema of your data.
Upvotes: 0