Home > database >  Convert result of separate arrays into one object using javascript
Convert result of separate arrays into one object using javascript

Time:11-01

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}

CodePudding user response:

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});
    }
  }
}
  • Related