【发布时间】:2023-03-06 13:41:01
【问题描述】:
我正在解析以下文件格式:
//网址//
帐户/42
//状态//
200
//标题//
content-type=application/json
//身体//
{“名称”:“xyz”}
//网址//
帐户/43
我想在 map 函数中为单个键存储多个值。
电流输出
{ url: [ undefined, 'account/42', undefined, 'account/43' ],
status: [ undefined, '200' ],
headers: [ undefined, 'content-type=application/json' ],
body: [ undefined, '{ "name": "xyz" }' ] }
预期输出
{ url: [ 'account/42', 'account/43' ],
status: [ '200' ],
headers: [ 'content-type=application/json' ],
body: [ '{ "name": "xyz" }' ] }
下面是代码
var fs = require('fs');
function parseFile(){
var content;
fs.readFile("src/main/resources/FileData1.txt", function(err, data) {
if(err) throw err;
content = data.toString().split(/(?:\r\n|\r|\n)/g).map(function(line){
return line.trim();
}).filter(Boolean)
console.log(processFile(content));
});
}
function processFile(nodes) {
var map={};
var key;
nodes.forEach(function(node) {
var value;
if(node.startsWith("//")){
key = node.substring(2, node.length-2).toLowerCase();
}
else{
value = node;
}
// map[key] = value;
if(key in map){
map[key].push(value);
}else{
map[key]= [value];
}
});
return map;
}
好的,我可以看到问题在于“值”的声明,因为我想存储多个值,但我不确定何时以及如何声明该值。即使我将值声明为全局值,它也会存储以前的值。 问题:如何在map中存储多个值?
【问题讨论】:
-
您对
url的预期输出有{ url: [ 'account/42',, 'account/43' ],为什么它的第二个值是空的? -
打印错误,我期望的 url 值应该是
code{url : ['account/42', 'account/43']
标签: javascript node.js hashmap