Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

60
Views
Convert result of separate arrays into one object using javascript

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}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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});
    }
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!