How to convert an object to a query string in TypeScript

3 Answers

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

 



answered Apr 21, 2022 by avibootz
0 votes
const obj = {
    q: 'TypeScript',
    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=TypeScript&lang=en&limit=10
   
*/

 



answered Apr 21, 2022 by avibootz
0 votes
const obj = {
    q: 'TypeScript',
    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=TypeScript&lang=en&limit=10
   
*/

 



answered Apr 21, 2022 by avibootz

Related questions

1 answer 217 views
1 answer 248 views
1 answer 197 views
3 answers 423 views
3 answers 329 views
1 answer 197 views
...