简体   繁体   中英

Is there a simple way to convert a complex JS object to query params?

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

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('&'); } 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM