0

I am running a code that returns a list of cities within a 30 mile radius of a user entered address. The result is x separate arrays being shown in the console (depending on the number of cities returned). I need to try and make these into 1 single object with the following format:

const citiesObject = [ { cityName: 'Vancouver', cityDistance: 3 }, { cityName: 'Paris', cityDistance: 4 }, { cityName: 'London', cityDistance: 1 }, ]

Here is my current for loop which returns the separate arrays:

var closestCities = {};
  for (var j = 0; j < results.length; j++) {

    // If distance is less than 30 miles (48280 metres)
    if(results[j].distance.value < 48280) {
      var closestCitiesDist = results[j].distance.value
      var closestCitiesName = origins[i]

      closestCities[j] = {"cityName" : closestCitiesName, "cityDistance" : closestCitiesDist}
      console.log(closestCities)
    }
  }
}

An example of what I am seeing in the console after a search is:

{cityName: 'Tamworth, UK', cityDistance: 24496}
{cityName: 'Birmingham, UK', cityDistance: 44338}

1 Answer 1

1

Convert closestCities to array and try not to use var. Array has a method push which allow you to add new item to end of array.

const closestCities = [];
  for (let j = 0; j < results.length; j++) {

    // If distance is less than 30 miles (48280 metres)
    if(results[j].distance.value < 48280) {
      const closestCitiesDist = results[j].distance.value
      const closestCitiesName = origins[i]

      closestCities.push({"cityName" : closestCitiesName, "cityDistance" : closestCitiesDist});
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.