How to convert URL parameters to a JavaScript object?

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

    A concise solution:

    location.search
      .slice(1)
      .split('&')
      .map(p => p.split('='))
      .reduce((obj, pair) => {
        const [key, value] = pair.map(decodeURIComponent);
        obj[key] = value;
        return obj;
      }, {});
    

提交回复
热议问题