[英]Customize map output in node 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数组中。
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
}
我已经测试了输入,现在应该可以正常工作了。 请检查并确认:)
我不确定您想要什么,但是我认为这段代码将帮助您:
var yourObj = { url: 'account/43', status: '200', headers: ['\\'content-type\\' = \\'application/json\\''], body: ['{ "name": "Fatma Zaman" }'] }; console.log('Your obj:'); console.log(yourObj); console.log('formatted:'); console.log(format(yourObj)); function format(obj) { for (var prop in obj) { if (typeof obj[prop] != 'object') { obj[prop] = obj[prop].replace(/"|'/g, ''); } else { obj[prop] = format(obj[prop]); } } return obj; }
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.