Home > front end >  How to iterate over object
How to iterate over object

Time:09-30

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.

CodePudding user response:

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)

CodePudding user response:

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: "[]" is the same as "[]" but it's URI encoded. It should be treated the same by the server.

CodePudding user response:

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)

  • Related