0

I have a JS object with nested arrays, take this one for example:

{
   array: [
    {
        name: 'test-1'
    },
    {
        name: 'test-2'
    }
   ]
   simpleParam: 1,
   complexParam: {
    attribute: 2
   }
}

I need to convert it to query params because the API I'm consuming needs to read them in the following format:

"array[0].name='test-1'&array[1].name='test-2'&simpleParam=1&complexParam.attribute=2"

I'd like to know if there's a simple way to do this like JSON.stringify() which in this case does not fit my needs or if I'd need to write my own generic algorithm to do this transformation.

EDIT I'd like to use plain JS and it's important to notice that there'd be arrays in the object I want to format

2 Answers2

2

This is from a class I wrote for something else:

var data = {
  array: [{
      name: 'test-1'
    },
    {
      name: 'test-2'
    }
  ],
  simpleParam: 1,
  complexParam: {
    attribute: 2
  }
};

var urlstring = stringifyObject(data);

console.log(urlstring);
console.log(decodeURIComponent(urlstring));

/**
 * Provided an object, it will convert it to a query string
 * @param data object to convert
 * @returns query string
 */
function stringifyObject(data) {
  var value, key, tmp = [];
  const encodeFunc = data => encodeURIComponent('' + data).replace(/!/g, '%21')
    .replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29')
    .replace(/\*/g, '%2A').replace(/%20/g, '+');
  const _hbqHelper = (key, val) => {
    var k, tmp = [];
    if (val === true) val = '1';
    else if (val === false) val = '0';
    if (val !== null) {
      if (typeof val === 'object') {
        for (k in val)
          if (val[k] !== null)
            tmp.push(_hbqHelper(key + '[' + k + ']', val[k], '&'));
        return tmp.join('&');
      } else if (typeof val !== 'function') return encodeFunc(key) + '=' + encodeFunc(val);
      else return false;
    } else return '';
  };
  for (key in data) {
    value = data[key];
    var query = _hbqHelper(key, value, '&');
    if (query === false) continue;
    if (query !== '') tmp.push(query)
  }
  return tmp.join('&');
}
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
0

You could do it like this with jQuery.param() and decodeURI() hoping the output is what you're looking for.

var myObj = {
   array: [
    {
        name: 'test-1'
    },
    {
        name: 'test-2'
    }
   ],
   simpleParam: 1,
   complexParam: {
    attribute: 2
   }
};

console.log(decodeURI($.param(myObj)));
// array[0][name]=test-1&array[1][name]=test-2&simpleParam=1&complexParam[attribute]=2
Lucas
  • 1,833
  • 1
  • 18
  • 19