[removed].search query as JSON

后端 未结 10 969
北海茫月
北海茫月 2020-12-24 14:51

Is there a better way to convert a URL\'s location.search as an object? Maybe just more efficient or trimmed down? I\'m using jQuery, but pure JS can work too.



        
10条回答
  •  半阙折子戏
    2020-12-24 15:42

    JSON Parse after stringify does the job of converting to a json with array data.

    ?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&

    {
         'key1' : 'val1',
         'key2' : [ 'val2.1', 'val2.2', 'val2.3' ]
    }
    

    function QueryParamsToJSON() {            
        var list = location.search.slice(1).split('&'),
            result = {};
    
        list.forEach(function(keyval) {
            keyval = keyval.split('=');
            var key = keyval[0];
            if (/\[[0-9]*\]/.test(key) === true) {
                var pkey = key.split(/\[[0-9]*\]/)[0];
                if (typeof result[pkey] === 'undefined') {
                    result[pkey] = [];
                }
                result[pkey].push(decodeURIComponent(keyval[1] || ''));
            } else {
                result[key] = decodeURIComponent(keyval[1] || '');
            }
        });
    
        return JSON.parse(JSON.stringify(result));
    }
    
    var query_string = QueryParamsToJSON();

提交回复
热议问题