0

I have an object like this:

  const params = {
     'userId[]': [1, 2],
     'empId': 2,
     advance: 'hello',
     };

and I want to make a string like this:

userId[]=1&userId[]=2&empId=2&advance=hello

I am trying like this:

 const myResult = Object.entries(params)
 .map(([key, value]) => {
  if (Array.isArray(value)) {
    let result;
    value.forEach(item => {
    `${key}=${value}`
    })
    return result
  }
 // return 
 })
 .join('&');

 console.log(myResult);

but not able to figure out what to do next.

techguy
  • 71
  • 8
  • Your params have empId = 2, but your desired string has empId = 5? Is this a typo? – kelsny Sep 30 '22 at 13:02
  • @caTS yah it was typo error. sorry – techguy Sep 30 '22 at 13:04
  • Related question: [Query-string encoding of a Javascript Object](https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object) – Yogi Sep 30 '22 at 13:07
  • https://stackoverflow.com/a/47164688/4826457 angular uses `HttpParams` object to build the URL params – Suraj Rao Sep 30 '22 at 13:18
  • @SurajRao but in google chrome,when there is any special charachter in query params, it automatically gets encoded, to avoid that I am trying to do in string format – techguy Sep 30 '22 at 13:22
  • Seems like reinventing the wheel since Angular already has methods for doing this and that can serialize arrays in the format it expects. – Yogi Sep 30 '22 at 13:58

3 Answers3

2

With a few changes, adding concatenation and non-array values:

const params = {
  "userId[]": [1, 2],
  empId: 2,
  advance: "hello",
}

const myResult = Object.entries(params)
  .map(([key, value]) => {
    // Assume non-array result as default
    let result = `${key}=${value}`

    if (Array.isArray(value)) {
      // Override for arrays
      const r = value
        .map((item) => {
          return `${key}=${item}`
        })
        .join("&")

      result = r
    }

    return result
  })
  .join("&")

console.log(myResult)
TheRemoteCoder
  • 172
  • 2
  • 12
1

URLSearchParams can do most of the work for us, but we still have to handle the array ourselves:

const params = {
  'userId[]': [1, 2],
  'empId': 2,
  advance: 'hello',
};

const p = new URLSearchParams();

for (const [key, value] of Object.entries(params)) {
    if (Array.isArray(value)) {
        for (const item of value) {
            p.append(key, item);
        }
    } else p.append(key, value);
}

console.log(p.toString());

Looping through the entries of our object, we check if the value is an array. If it isn't we append it, otherwise, we append all its items. URLSearchParams makes the string for us; all we do is tell it what to use for the string :)

Note: "%5b%5D" is the same as "[]" but it's URI encoded. It should be treated the same by the server.

kelsny
  • 23,009
  • 3
  • 19
  • 48
  • I need it in string format only. because while I am making api call it will get encoded. to avoid that I am doing all these things, i mean I want it in string only – techguy Sep 30 '22 at 13:10
  • @techguy Why? It will get URI encoded anyways. – kelsny Sep 30 '22 at 13:11
  • no, if we are making it string and appending it to url directly, then it is working fine, I tried it. I am using Angular framework – techguy Sep 30 '22 at 13:13
0

You can do the following instead of iterating over the object: url = Object.keys(params).map(function(k) {return k + '=' + params[k]}).join('&')"

which would give you 'userId[]=1,2&empId=2&advance=hello' I think you need this(guessing that you made a typo error)

unlimit
  • 21
  • 7