Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading