Skip to content

Instantly share code, notes, and snippets.

@tinabme
Created August 18, 2016 20:56
Show Gist options
  • Save tinabme/2a9930509c1df935266f38c8730e7e58 to your computer and use it in GitHub Desktop.
Save tinabme/2a9930509c1df935266f38c8730e7e58 to your computer and use it in GitHub Desktop.
Param() for JavaScript -- no jQuery needed. Returns a serialized (url encoded) representation of an array or object for use in URL query string or Ajax request, without jQuery. Raw

Param() for JavaScript -- no jQuery needed

Returns a serialized (url encoded) representation of an array or object for use in URL query string or Ajax request, without jQuery.

Javascript Code

function param(obj) {
  let result = '';
  for (let key of Object.keys(obj)) {
    // if obj[key] is an object dig deeper
    if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
      result += (result ? '&' : '') + objectParam(obj[key], key, 1);
    } else {
      result += (result ? '&' : '') +
        encodeURIComponent(key) + '=' +
        encodeURIComponent(obj[key] || '');
    }
  }
  return result;
}

function objectParam(obj, name, lvl) {
  let rtn = '';
  // make sure an object was passed and only go 3 levels deep 
  if (Object.prototype.toString.call(obj) === '[object Object]' && lvl < 4) {
    lastElement = Object.keys(obj)[Object.keys(obj).length - 1];
    rtn += (rtn ? '&' : '') + encodeURIComponent(name) + '=%7B';
    for (let key1 of Object.keys(obj)) {
      if (Object.prototype.toString.call(obj[key1]) === '[object Object]') {
        rtn += (rtn ? '&' : '') + objectParam(obj[key1], key1, lvl + 1);
      } else {
        rtn += encodeURIComponent(key1) + ':' +
          encodeURIComponent(obj[key1] || '') +
          (key1 != lastElement ? ',' : '');
      }
    }
    rtn += '%7D';
  }
  return rtn;
}

Usage Examples

A simple object Example

let myObj = {
  car: 'Pinto',
  color: 'red',
  doors: '2',
  transmission: 'Auto'
};
const url = '/someurl?' + param(myObj);
// returns  '/someurl?car=Pinto&color=red&doors=2&transmission=Auto'

Complex object Example (An object that has a vaue of an array & another object)

let mylayObj = {
  car: 'Pinto',
  color: ['red', 'green', 'orange'],
  doors: '2',
  transmission: {
    Auto: '4 cyl',
    Manuel: '4 cal'
  }
};

const url = '/someurl?' + param(mylayObj);
// returns  '/someurl?car=Pinto&color=red%2Cgreen%2Corange&doors=2&transmission=%7BAuto:4%20cyl,Manuel:4%20cal%7D'

See it work on jsFiddle

param - serialized/url encode an object

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment