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

how to take a value from nested object in headers

  headers: {
    host: 'localhost:3000',
    connection: 'keep-alive',
    'cache-control': 'max-age=0',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"macOS"',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36',



Code: 

    const user: User = req['user'];
    return {
      userAgent: {
        agent: req.headers.connection.reduce((el) =>
          Object.fromEntries(
            Object.entries(el).map(([k, v]) => [k, Object.values(v)[0]]),
          ),
        ),
      },
      headers: req.headers,
    };
  }
}


I have to take user-agent from connection. 


 I have used the map and reduce function but its says map cannot be used for string. 

If i am doing req.headers.connection i am getting only "keep-alive"

i have also used. req.headers.connection[6], but didn’t get the desired result.

desired result is getting user-agent from connection

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

>Solution :

req.headers.connection is a single item. Maybe you’re getting confused because the other keys of req.headers have quotes. This should work:

return {
  userAgent: {
    agent: req.headers["user-agent"]
  },
  headers: req.headers,
};
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