如何从 headers 中的嵌套 object 中获取值

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. 

如果我正在做 req.headers.connection 我只会得到“keep-alive”

我也用过。 req.headers.connection[6],但没有得到想要的结果。

期望的结果是从连接

获得 user-agent

req.headers.connection是单品。也许您感到困惑,因为 req.headers 的其他键有引号。这应该有效:

return {
  userAgent: {
    agent: req.headers["user-agent"]
  },
  headers: req.headers,
};