Plain Javascript Equivalent of jQuery.param()

后端 未结 7 1257
小蘑菇
小蘑菇 2021-02-07 11:04

jQuery.param() takes an array of key-value pairs, and turns it into a string you can use as a query string in HTML requests. For example,

a = {
      userid:1,
         


        
7条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 11:32

    most solutions here fail on array/object values.

    this will support arrays/objects of the first level:

    const param = obj => Object.entries(obj).map(
        pair => Array.isArray(pair[1]) ?
            pair[1].map(x=>`${encodeURIComponent(pair[0])}[]=${encodeURIComponent(x)}`).join('&') :
            typeof pair[1] === 'object' ? 
            Object.entries(pair[1]).map(x=>`${encodeURIComponent(pair[0])}[${x[0]}]=${encodeURIComponent(x[1])}`).join('&') :
            pair.map(encodeURIComponent).join('=')).join('&')
    

    examples:

    param({a:1,b:'b'})
    "a=1&b=b"
    
    param({a:1,b:2,c:[1,2],d:{e:'abc',f:4}});
    "a=1&b=2&c[]=1&c[]=2&d[e]=abc&d[f]=4"
    
    param({a:1,b:2,c:[1,2,'"'],d:{e:'a"b[c]',f:4}});
    "a=1&b=2&c[]=1&c[]=2&c[]=%22&d[e]=a%22b%5Bc%5D&d[f]=4"
    

    however, note that it fails on 2nd level (nesting):

    param({a:1,b:{c:[1,2]}});
    "a=1&b[c]=1%2C2"
    

提交回复
热议问题