Home > front end >  How can I reconstruct raw headers from request into an array?
How can I reconstruct raw headers from request into an array?

Time:06-16

I am trying to reconstruct the raw headers from the request object from looking like this:

[{"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?

CodePudding user response:

You can first flatMap() them to an array of values and then reduce() them pairwise to your desired result 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);

  • Related