+ 2

How to loop though object of key value pair and print them in format of name value each from new line in javascript

i am trying to have access to http request.header which will give as an object i want to loop and print them on the screen using response.write NODE JS

16th Aug 2020, 11:30 AM
Abdulaziz Abdurasul
Abdulaziz Abdurasul - avatar
13 odpowiedzi
+ 1
Abdulaziz Abdurasul Here another way using for in iteration: const http = require('http'); const server = http.createServer((request, response)=>{ response.writeHead(200, {'Content-Type': 'text/plain'}); for (const key in request.headers) { response.write(`${key}: ${request.headers[key]}`); } response.end(); }).listen(3000);
16th Aug 2020, 12:24 PM
Calviղ
Calviղ - avatar
+ 2
Abdulaziz Abdurasul My apologies, I didn't read your question fully.
16th Aug 2020, 12:16 PM
Russ
Russ - avatar
+ 1
Abdulaziz Abdurasul Here the code you are looking for: const http = require('http'); const server = http.createServer((request, response)=>{ response.writeHead(200, {'Content-Type': 'text/plain'}); for (const [key, value] of Object.entries(request.headers)) { response.write(`${key}: ${value}`); } response.end(); }).listen(3000);
16th Aug 2020, 12:15 PM
Calviղ
Calviղ - avatar
+ 1
Abdulaziz Abdurasul Object.entries(obj) returns both the object keys and values.
16th Aug 2020, 5:59 PM
Infinite
Infinite - avatar
+ 1
Abdulaziz Abdurasul In case you're still curious about Object.entries() static method, check this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
17th Aug 2020, 7:55 PM
Samuel Adepoju
Samuel Adepoju - avatar
0
Use the for..in loop. for (let key in object_name) { let value = object_name[key]; }
16th Aug 2020, 11:52 AM
XXX
XXX - avatar
0
XXX it doesn't work the way its expected
16th Aug 2020, 12:02 PM
Abdulaziz Abdurasul
Abdulaziz Abdurasul - avatar
0
XXX Looping through object and printing name value each in new line ;
16th Aug 2020, 12:03 PM
Abdulaziz Abdurasul
Abdulaziz Abdurasul - avatar
0
Russ try to creare a server with http module in Node js and console log the ruquest.headers
16th Aug 2020, 12:14 PM
Abdulaziz Abdurasul
Abdulaziz Abdurasul - avatar
0
const http = require("http); const server = http.createSeever(function(req,res){ console.log(req.headers); });
16th Aug 2020, 12:16 PM
Abdulaziz Abdurasul
Abdulaziz Abdurasul - avatar
0
Calviղ is there any other ways for not using Object.enties coz i have to submit this code in onle online web there is bot checking the code it will not accept this way
16th Aug 2020, 12:18 PM
Abdulaziz Abdurasul
Abdulaziz Abdurasul - avatar
0
Calviղ and sorry Calvin u are very amazing guy i really appreciate u work🙏🙏 can u please in simple way explain the way and what this Objec.enties does ?
16th Aug 2020, 12:20 PM
Abdulaziz Abdurasul
Abdulaziz Abdurasul - avatar