0

I have an object with filter value I want to form a query params based on the object, pls help

object = {
  emp_id: 1, 
  firstname: abc, 
  lastname: xyz, 
  mobile: 12345, 
  email: xyz@123.com
}

url = emp_id=1&firstname=abc&lastname=xyz&mobile=12345&email=xyz@123.com

for (const [key, value] of Object.entries(object)) {
 url = `${key}= ${value}&`;
}

here im getting only the last value

Vishnu Shenoy
  • 862
  • 5
  • 18
  • Use `.map()` then `.join()` on the array instead. (also please look for existing answers before posting a question) –  May 31 '21 at 09:17
  • 1
    I'd use a [`URLSearchParams` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams), which you can construct using the result from `Object.entries` directly: `const params = new URLSearchParams(Object.entries(object));` Then if you need a query string, use `const str = params.toString();` – T.J. Crowder May 31 '21 at 09:18
  • why the for loop is not working – Vishnu Shenoy May 31 '21 at 09:19
  • @VishnuShenoy It's hard to be sure because the code shown has multiple syntax errors and missing parts, but it's probably because you're **replacing** `url` on each loop iteration, not adding to it (you have `=`, not `+=`). Also note that you need to URI-encode the keys and values, you can't just use them directly. – T.J. Crowder May 31 '21 at 09:21
  • got a simple solution url = new URLSearchParams(object).toString() – Vishnu Shenoy May 31 '21 at 10:56

0 Answers0