Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform `Request` headers to plain key value object

I am trying to convert a list of headers from a Request (see https://developer.mozilla.org/en-US/docs/Web/API/Request/headers) object to a plain key/value object.

// Create a Request object.
const req = new Request('https://example.com', {
    headers: {
        'X-Test-header': 'Test'
    }
});

Sadly, the following doesn’t work because the headers property is an iterator:

Unusable result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const result1 = JSON.stringify(req.headers);
// result1 =  `{}`

Usable result but very verbose to create:

const headers = {};
for(const [key, value] of req.headers.entries()) {
    headers[key] = value;
}
const result2 = JSON.stringify(headers)
// result2 = `{'X-Test-Header': 'Test'}`

I’m looking for some sort of a one liner (maybe including Array.from() or some of the other methods on the Request.headers object like .keys()/.values() so that I am able to stringify the result.

>Solution :

You could use the Object.fromEntries() method, and then stringify that object like below. The .fromEntries() method will invoke the iterator of your headers object (ie: the .entries()) to grab the entries of the header object, and then use that to create an object. You can then pass this to JSON.stringify() to get your JSON string:

const req = new Request('https://example.com', {
    headers: {
        'X-Test-header': 'Test'
    }
});

const result1 = JSON.stringify(Object.fromEntries(req.headers));
console.log(result1);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading