How to convert URL parameters to a JavaScript object?

前端 未结 30 1366
时光取名叫无心
时光取名叫无心 2020-11-22 13:57

I have a string like this:

abc=foo&def=%5Basf%5D&xyz=5

How can I convert it into a JavaScript object like this?

{
          


        
30条回答
  •  时光取名叫无心
    2020-11-22 14:45

    Building on top of Mike Causer's answer I've made this function which takes into consideration multiple params with the same key (foo=bar&foo=baz) and also comma-separated parameters (foo=bar,baz,bin). It also lets you search for a certain query key.

    function getQueryParams(queryKey) {
        var queryString = window.location.search;
        var query = {};
        var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
        for (var i = 0; i < pairs.length; i++) {
            var pair = pairs[i].split('=');
            var key = decodeURIComponent(pair[0]);
            var value = decodeURIComponent(pair[1] || '');
            // Se possui uma vírgula no valor, converter em um array
            value = (value.indexOf(',') === -1 ? value : value.split(','));
    
            // Se a key já existe, tratar ela como um array
            if (query[key]) {
                if (query[key].constructor === Array) {
                    // Array.concat() faz merge se o valor inserido for um array
                    query[key] = query[key].concat(value);
                } else {
                    // Se não for um array, criar um array contendo o valor anterior e o novo valor
                    query[key] = [query[key], value];
                }
            } else {
                query[key] = value;
            }
        }
    
        if (typeof queryKey === 'undefined') {
            return query;
        } else {
            return query[queryKey];
        }
    }
    

    Example input: foo.html?foo=bar&foo=baz&foo=bez,boz,buz&bar=1,2,3

    Example output

    {
        foo: ["bar","baz","bez","boz","buz"],
        bar: ["1","2","3"]
    }
    

提交回复
热议问题