javascript - 从 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));
。但这并没有让我得到我想要的输出。
请建议我如何获得所需的输出。欢迎任何建议。谢谢!
解决方案
要将数组转换为对象:
let arr = [
{ "country1": { "capital": "some capital", "currency": "$" } },
{ "country2": { "capital": "some capital", "currency": "$" } }
];
let obj = Object.assign({}, ...arr);
console.log(obj);
推荐阅读
- android - 动态更新新闻应用程序的视图(viewpager)
- javascript - 返回带有 onclick cookie 值的 html 按钮
- ksh - 在 shell 中获取错误的数字
- ruby-on-rails - 如何使用数据库条目作为 ruby on rails 的元描述
- python-3.x - 如何从长度小于 7 个字母的字典中删除值?
- pytorch - 如何在 pytorch 中执行 RNN 的推出
- javascript - 向前运行的JS循环,到达终点然后无限期地向后和向前运行
- python - Python字符串怎么可能是数字?
- c++ - 如何将向量行(点)对齐到中心?
- c - 当您不知道字符串有多长时,从 C 中的用户输入中拆分字符串