hidace hidace - 5 months ago 13
JSON Question

Getting null when looping through JSON and writing to a file in node

I'm looping through 2 JSON objects. One contains an array of country objects and the other is an array of airport objects. I'd like to loop through and return a model that combines information from both if that airport's country matches the current country:

const fs = require('fs');
const allData = require('./airports.json');
const countryCodes = require('./codes.json');

const newData = countryCodes.map(country => {
allData.map(airport => {
if (country.name === airport.country) {
// console.logging here shows me that my equality check is working...
return {
"airport": `${airport.code} - ${airport.name}`,
"countryName": `${airport.country}`,
"countryCode": `${country["alpha-2"]}`
}
}
})
})

fs.writeFile("./newAirlines.json", JSON.stringify(newData, null, 2), function(err) {
if (err) {
console.log(err);
}
});


However, when I open the newAirlines.json file it writes to, I just get an array of null, null, null... Wondering if this has something to do with the asynchronously trying to write to a file before it has a chance to finish looping through (?), but am not sure.

Any and all help is appreciate. Thanks!

Answer

Your newData variable is not returning anything. You should populate an array an from inside the second iteration instead of calling map again on the airport array. For example:

    const newAirlines = []
    const newData = countryCodes.forEach(country => {    
      allData.forEach(airport => {
        if (country.name === airport.country) {
          newAirlines.push({
            "airport": `${airport.code} - ${airport.name}`,
            "countryName": `${airport.country}`,
            "countryCode": `${country["alpha-2"]}`
          })
        }
      })
     })

    fs.writeFile("./newAirlines.json", JSON.stringify(newAirlines, null, 2), function(err) {
      if (err) {
        console.log(err);
      }
    })