首页 > 解决方案 > 从 json 文件读取时,如何返回对象而不是数组中的对象?

问题描述

我正在从目录中读取一些 json 文件并将它们用作端点。我有以下代码:

 fs.readdir(dirPath, function (err, filesPath) {
            if (err) throw err;
            filesPath = filesPath.map(function(filePath){ 
                return dirPath + filePath;
            });
            async.map(filesPath, function(filePath, cb){ 
                fs.readFile(filePath, 'utf8', cb);
            }, function(err, results) {
                res.send(results);
            });
        });

这将返回如下内容:

[         
  {
    "Country1":{
       "countryTEST":"US",
       "FindLocale":{
          "Test":{
             "Test":false,
             "Test":""
          },
          "Test":{
             "Test":false,
             "Test":"value"
          }
       },
        "payment":[
          "CREDIT_CARD",
          "NOT_CREDIT"
       ],
       "test":"1234",
       "phoneNumb":[
          ""
       ]
    },

    "Country2":{
       "countryTEST":"US",
       "FindLocale":{
          "Test":{
             "Test":false,
             "Test":""
          },
          "Test":{
             "Test":false,
             "Test":"value"
          }
       },
        "payment":[
          "CREDIT_CARD",
          "NOT_CREDIT"
       ],
       "test":"1234"
       "phoneNumb":[
          ""
       ]
    }
  }
]

但是,我希望返回的响应看起来像这样(没有包装对象的数组)

 {
    "Country1":{
       "countryTEST":"US",
       "FindLocale":{
          "Test":{
             "Test":false,
             "Test":""
          },
          "Test":{
             "Test":false,
             "Test":"value"
          }
       },
        "payment":[
          "CREDIT_CARD",
          "NOT_CREDIT"
       ],
       "test":"1234"
       "phoneNumb":[
          ""
       ]
    },

    "Country2":{
       "countryTEST":"US",
       "FindLocale":{
          "Test":{
             "Test":false,
             "Test":""
          },
          "Test":{
             "Test":false,
             "Test":"value"
          }
       },
        "payment":[
          "CREDIT_CARD",
          "NOT_CREDIT"
       ],
       "test":"1234"
       "phoneNumb":[
          ""
       ]
    }
  }

我试过做类似的事情res.send(JSON.stringify(results));res.send(JSON.parse(results));。但这并没有让我得到我想要的输出。

请建议我如何获得所需的输出。欢迎任何建议。谢谢!

标签: javascriptnode.jsarraysjsonparsing

解决方案


要将数组转换为对象:

let arr = [
    { "country1": { "capital": "some capital", "currency": "$" } },
    { "country2": { "capital": "some capital", "currency": "$" } }
];
let obj = Object.assign({}, ...arr);
console.log(obj);


推荐阅读