How to convert an object to a query string in Node.js

3 Answers

0 votes
const obj = {
    q: 'NodeJS',
    lang: 'en',
    limit: 10
};
 
const queryString = '?' + new URLSearchParams(obj).toString();
 
console.log(queryString); 
 
   
   
   
   
/*
run:
   
?q=NodeJS&lang=en&limit=10
   
*/

 



answered Apr 21, 2022 by avibootz
0 votes
const obj = {
    q: 'NodeJS',
    lang: 'en',
    limit: 10
};
 
const queryString = Object.keys(obj)
    .map(key => `${key}=${obj[key]}`)
    .join('&');
 
console.log(`https://seek4info.com?${queryString}`);
 
   
   
   
   
/*
run:
   
https://seek4info.com?q=NodeJS&lang=en&limit=10
   
*/

 



answered Apr 21, 2022 by avibootz
0 votes
const obj = {
    q: 'NodeJS',
    lang: 'en',
    limit: 10
};
 
const queryString = Object.keys(obj)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
    .join('&');
     
     
console.log(`https://seek4info.com?${queryString}`);
 
   
   
   
   
/*
run:
   
https://seek4info.com?q=NodeJS&lang=en&limit=10
   
*/

 



answered Apr 21, 2022 by avibootz

Related questions

1 answer 132 views
3 answers 258 views
2 answers 251 views
2 answers 209 views
209 views asked Feb 27, 2020 by avibootz
1 answer 210 views
3 answers 361 views
1 answer 151 views
...