0

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.

Shahaparan
  • 23
  • 7
  • 1
    btw why use " " in query string since it will always be a string when capturng from server side. also the true will also be a string "true" when caught in server – cmgchess Aug 07 '22 at 09:28
  • Basically, I want to get object values to query string if it's bolean. – Shahaparan Aug 07 '22 at 09:31
  • Does this answer your question? [Query-string encoding of a Javascript Object](https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object) – PiFanatic Aug 07 '22 at 09:32
  • No, I actually want to get like from { param1: 'test', param2: true, } to value "test=true" – Shahaparan Aug 07 '22 at 09:37
  • This seem like an x/y problem. _Why_ does `NO` have to be in quotes? – Andy Aug 07 '22 at 09:41

2 Answers2

2

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)
Konrad
  • 21,590
  • 4
  • 28
  • 64
1

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)
MarkusAfricanus
  • 113
  • 1
  • 16