javascript - 在节点 JS 中自定义地图输出
问题描述
由于我在 map 中有 4 个键/值,我试图以字符串格式存储两个键并将两个键放在一个数组中,但它没有采用数组的多个值。
现在我得到什么输出:
{ url: 'account/43',
status: '200',
headers: [ '\'content-type\' = \'application/json\'' ],
body: [ '{ "name": "Fatma Zaman" }' ]}
预期输出:
{ url: 'account/43',
status: '200' ,
headers:
[ 'content-type = application/json',
'content-type = application/text' ],
body: [ '{ name: Fatma Zaman }' ] }
下面是返回多个标题值但所有键都是数组格式或字符串中的 url/status 和数组中的 headers/body 的代码。
function processFile(content) {
content.forEach(function(node) {
if (node.startsWith("//")) {
key = node.substring(2, node.length-2).toLowerCase().trim()
return
} else {
value = node
}
if (key in map) {
map[key].push(value)
} else {
map[key]= [value]
}
map[key] = ["headers", "body"].includes(key)? [value] : value
})
return map
}
如果我添加下面的代码,它会给我多个值,但不是 url/body 不是字符串
if (key in map) {
map[key].push(value)
} else {
map[key]= [value]
}
简而言之,我无法同时实现两者。像带有字符串格式的 url/status 的多个标头值。任何帮助和建议将不胜感激
这是完整的代码
const fs = require("fs")
const path = require("path")
let key
let value
let filePath
function parseFile(filePath) {
filePath = path.join(__dirname, "../resources/FileData1.txt")
fs.readFile(filePath, 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(content) {
content.forEach(function(node) {
if (node.startsWith("//")) {
key = node.substring(2, node.length-2).toLowerCase().trim()
return
} else {
value = node
}
if (key in map) {
map[key].push(value)
} else {
map[key] = value
}
// map[key] = ["headers", "body"].includes(key)? [value] : value
})
return map
}
parseFile(filePath)
module.exports = {parseFile, processFile}
输入格式如下:
//Status//
200
//HEADERS//
content-type = application/json
//BODY//
{ name: Fatma Zaman }
//URL//
account/43
//HEADERS//
content-type = application/text
解决方案
请尝试以下代码:
function processFile(content) {
let map ={};
content.forEach(function(node) {
if (node.startsWith("//")) {
key = node.substring(2, node.length-2).toLowerCase().trim()
return
} else {
value = node
}
if (["headers", "body"].includes(key)) {
if(map[key]){
map[key].push(value);
}else{
map[key] = [value]
}
} else {
map[key]= value
}
})
return map
}
现在应该可以了,我已经用输入进行了测试。请检查并确认:)
推荐阅读
- python - 仅反转字符链接列表中的元音
- mysql - 如何比较不同表的SQL字段,然后用值替换其他字段?
- python - 如何解决“'NoneType'类型的参数不可迭代”的问题?
- flutter - 对框架中不存在的类进行 Flutter 模糊导入
- javascript - Netlify Lambda 不包含 Function 的支持文件
- python - 在 Panda DataFrame 中隐藏索引的最佳方法是什么?
- android - 切换到新页面时使用抽屉时出现颤振错误
- javascript - 如果我调用 Just Object,则获取特定属性而不是 Object
- intellij-plugin - Intellij 自定义插件不起作用它说清单丢失或无法识别主类
- r - 对具有分组数据的 purrr map() 中的特定列使用 dplyr summarise()