【问题标题】:Getting null when looping through JSON and writing to a file in node循环通过 JSON 并写入节点中的文件时获取 null
【发布时间】:2016-06-28 17:41:44
【问题描述】:

我正在循环 2 个 JSON 对象。一个包含一组国家对象,另一个是一组机场对象。如果该机场的国家/地区与当前国家/地区匹配,我想循环并返回一个结合了两者信息的模型:

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 的数组...想知道这是否与在文件之前异步尝试写入文件有关有机会完成循环(?),但不确定。

感谢所有帮助。谢谢!

【问题讨论】:

    标签: javascript json node.js


    【解决方案1】:

    您的 newData 变量没有返回任何内容。您应该从第二次迭代中填充一个数组,而不是在机场数组上再次调用 map。例如:

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

    【讨论】:

    • 太好了,这确实解决了我的问题。感谢您的帮助!
    • 随时。附注:我相当确定您对 fs.writeFIle() 的调用将等到所有代码执行之前。这些 Array 方法是同步运行的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2015-06-07
    相关资源
    最近更新 更多