简体   繁体   English

如何将请求中的原始标头重建为数组?

[英]How can I reconstruct raw headers from request into an array?

I am trying to reconstruct the raw headers from the request object from looking like this:我正在尝试从请求 object 中重建原始标头,如下所示:

[{"0": "Host"},
 {"1": "localhost:3000"},
 {"2": "Connection"},
 {"3": "keep-alive"}, 
{"4": "sec-ch-ua"}, 
{"5": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\""}]

to something like:类似于:

[{ "Host: "localhost:3000"}, {"Connection": "Keep alive"}]

is this possible in javascript?这在 javascript 中可能吗?

You can first flatMap() them to an array of values and then reduce() them pairwise to your desired result object:您可以先将它们flatMap()到一个数组,然后将它们成对地reduce()到您想要的结果 object:

 const headers = [ {"0": "Host"}, {"1": "localhost:3000"}, {"2": "Connection"}, {"3": "keep-alive"}, {"4": "sec-ch-ua"}, {"5": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\""} ]; const result = headers.flatMap(Object.values).reduce((r, _, i, a) => i % 2? r: {...r, [a[i]]: a[i + 1] }, {}); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM