简体   繁体   中英

Building a JSON from a database query of country, state, city and each cities latitude/longitude

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;
}

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 eg none , you could also do the same for the latitude and longitude .

However, I would recommend reconsidering the schema of your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM