How to convert URL parameters to a JavaScript object?

前端 未结 30 1028
时光取名叫无心
时光取名叫无心 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:19

    If you are using URI.js, you can use:

    https://medialize.github.io/URI.js/docs.html#static-parseQuery

    var result = URI.parseQuery("?foo=bar&hello=world&hello=mars&bam=&yup");
    result === {
      foo: "bar",
      hello: ["world", "mars"],
      bam: "",
      yup: null
    };
    
    0 讨论(0)
  • 2020-11-22 14:19

    One simple answer with build in native Node module.(No third party npm modules)

    The querystring module provides utilities for parsing and formatting URL query strings. It can be accessed using:

    const querystring = require('querystring');
    
    const body = "abc=foo&def=%5Basf%5D&xyz=5"
    const parseJSON = querystring.parse(body);
    console.log(parseJSON);
    
    0 讨论(0)
  • 2020-11-22 14:20

    Here's my quick and dirty version, basically its splitting up the URL parameters separated by '&' into array elements, and then iterates over that array adding key/value pairs separated by '=' into an object. I'm using decodeURIComponent() to translate the encoded characters to their normal string equivalents (so %20 becomes a space, %26 becomes '&', etc):

    function deparam(paramStr) {
        let paramArr = paramStr.split('&');     
        let paramObj = {};
        paramArr.forEach(e=>{
            let param = e.split('=');
            paramObj[param[0]] = decodeURIComponent(param[1]);
        });
        return paramObj;
    }
    

    example:

    deparam('abc=foo&def=%5Basf%5D&xyz=5')
    

    returns

    {
        abc: "foo"
        def:"[asf]"
        xyz :"5"
    }
    

    The only issue is that xyz is a string and not a number (due to using decodeURIComponent()), but beyond that its not a bad starting point.

    0 讨论(0)
  • 2020-11-22 14:21

    Another solution based on the latest standard of URLSearchParams (https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

    function getQueryParamsObject() {
      const searchParams = new URLSearchParams(location.search.slice(1));
      return searchParams
        ? _.fromPairs(Array.from(searchParams.entries()))
        : {};
    }
    

    Please note that this solution is making use of

    Array.from (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

    and _.fromPairs (https://lodash.com/docs#fromPairs) of lodash for the sake of simplicity.

    It should be easy to create a more compatible solution since you have access to searchParams.entries() iterator.

    0 讨论(0)
  • 2020-11-22 14:22

    ES6 one liner. Clean and simple.

    Object.fromEntries(new URLSearchParams(location.search));
    

    For your specific case, it would be:

    console.log(
      Object.fromEntries(new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5'))
    );

    0 讨论(0)
  • 2020-11-22 14:22

    Split on & to get name/value pairs, then split each pair on =. Here's an example:

    var str = "abc=foo&def=%5Basf%5D&xy%5Bz=5"
    var obj = str.split("&").reduce(function(prev, curr, i, arr) {
        var p = curr.split("=");
        prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
        return prev;
    }, {});
    

    Another approach, using regular expressions:

    var obj = {}; 
    str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
        obj[decodeURIComponent(key)] = decodeURIComponent(value);
    }); 
    

    This is adapted from John Resig's "Search and Don’t Replace".

    0 讨论(0)
提交回复
热议问题