2016-06-28 60 views
0

我正在循環訪問2個JSON對象。一個包含一個國家對象數組,另一個是機場對象數組。我想通過循環,並返回來自兩個如果機場的國目前的國家相匹配的信息相結合的典範:當通過JSON循環並寫入節點中的文件時爲null

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

然而,當我打開newAirlines.json文件寫入到,我只是得到一個數組null,null,null ...想知道這是否與異步嘗試寫入文件之前有一個機會完成循環(?),但我不確定。

任何和所有的幫助是感謝。謝謝!

回答

1

你的newData變量沒有返回任何東西。您應該從第二次迭代中填充數組,而不是再次在機場數組上調用映射。例如:

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); 
     } 
    }) 
+0

很好,那確實解決了我的問題。感謝幫助! – hidace

+0

隨時。一個方面的說明:我相當肯定你對fs.writeFIle()的調用將等待所有的代碼執行之前。這些數組方法正在同步運行。 – morecchia808