Guest User

Untitled

a guest
Jan 18th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.54 KB | None | 0 0
  1. /*
  2. This function takes in an array of objects:
  3. [
  4. {
  5. param: 'value'
  6. },
  7. {
  8. anotherParam: 'another value'
  9. }
  10. ]
  11. */
  12. function constructQueryString(params) {
  13. if (typeof params !== 'object' || ! params.length) {
  14. throw new Error('Params must be an array');
  15. }
  16. let string = '';
  17. // Loop through params
  18. for (let i = 0; i < params.length; i++) {
  19. const key = Object.keys(params[i])[0];
  20. const value = params[i][key];
  21.  
  22. if (i === 0) {
  23. string += `?${ key }=${ value }`;
  24. } else {
  25. string += `&${ key }=${ value }`;
  26. }
  27. }
  28. return encodeURI(string);
  29. }
Add Comment
Please, Sign In to add comment