Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
How to convert from object to query string in javascript

I am trying to convert values to query string.

var obj = {
  param1: 'test',
  param2: true,
}

var str = "";

for (var key in obj) {
  if (str != "") {
    str += "&";
  }
  str += key + "=" + obj[key];
}

console.log(str);

Expected query string would be like this: test=true.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It would be much easier if you would use objects as intended but:

const obj = {
  param1: 'test',
  param2: 'true',
  param3: 'test2',
  param4: 'NO',
}

const entries = Object.values(obj)

const trueObj = {}
for (let i = 0; i < entries.length; i += 2) {
  trueObj[entries[i]] = entries[i + 1]
}

const params = new URLSearchParams(trueObj)

const queryString = params.toString()

console.log(queryString)

about 4 years ago · Juan Pablo Isaza Report

0

You can use back ticks to insert the quote. You will however, have to write a bit of extra logic in you obj variable to determine which parameters should be passed as a string or just the value.

const string = `"NO"`;
console.log(string)

about 4 years ago · Juan Pablo Isaza Report

0

var obj = {
  param1: 'test',
  param2: 'true',
  param3: 'test2',
  param4: 'NO',
}

var str = "";
var i = 0; 
for (var key in  obj) {
  if(i%2 ===0)   {
   if(i!== 0) 
    str +=   "&" + obj[key]  + "=";
 else  str +=    obj[key]  + "=";
  }
else   str +=  obj[key]  ;
i++;
}

console.log(str);

That should work as intended.
Results:
test=true&test2=NO

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!