1

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.

5
  • 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 Commented Aug 7, 2022 at 9:28
  • Basically, I want to get object values to query string if it's bolean. Commented Aug 7, 2022 at 9:31
  • Does this answer your question? Query-string encoding of a Javascript Object Commented Aug 7, 2022 at 9:32
  • No, I actually want to get like from { param1: 'test', param2: true, } to value "test=true" Commented Aug 7, 2022 at 9:37
  • This seem like an x/y problem. Why does NO have to be in quotes? Commented Aug 7, 2022 at 9:41

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

4 Comments

my Expected result would be : test=true&test2="NO"
How do you distinguish which one should be wrapped in "" if both types are string? Why your object don't look like this: { test: true, test2: 'NO' }
one would be string and other would-be bolean
In your questions both are string, true in javascript is written without quotes
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.