首页 > 解决方案 > 在节点 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

标签: javascriptnode.js

解决方案


请尝试以下代码:

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 
}

现在应该可以了,我已经用输入进行了测试。请检查并确认:)


推荐阅读