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: [email protected]
}

url = emp_id=1&firstname=abc&lastname=xyz&mobile=12345&[email protected]

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

here im getting only the last value

5
  • Use .map() then .join() on the array instead. (also please look for existing answers before posting a question) Commented May 31, 2021 at 9:17
  • 1
    I'd use a URLSearchParams object, 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(); Commented May 31, 2021 at 9:18
  • why the for loop is not working Commented May 31, 2021 at 9: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. Commented May 31, 2021 at 9:21
  • got a simple solution url = new URLSearchParams(object).toString() Commented May 31, 2021 at 10:56

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.