Plain Javascript Equivalent of jQuery.param()

后端 未结 7 1241
小蘑菇
小蘑菇 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:27

    You can also do that with pure JavaScript, but you have to write more lines of code. Try this:

    HTML code for testing:

    <p id="test"></p>
    

    JavaScript to be fired onload:

    a = {
          userid:1,
          gender: "male",
        }
    
    url = Object.keys(a).map(function(k) {
        return encodeURIComponent(k) + '=' + encodeURIComponent(a[k])
    }).join('&')
    
    document.getElementById("test").innerHTML=url
    

    The output is this:

    userid=1&gender=male
    

    You can try this on JSFIDDLE.NET, it works, here's the link: http://jsfiddle.net/ert93wbp/

    0 讨论(0)
  • 2021-02-07 11:29

    This was a bit frustrating. None of the solutions here seemed to actually work to produce actual "x-www-form-urlencoded" data for any JSON object, the equivalent of JQuery. Some came close but failed on child items. I pieced code from a few of the solutions to get this, working version for any JSON object:

    function formData (obj) {
      return Object.keys(obj).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(JSON.stringify(obj[k]))).join('&')
    }
    

    FYI I had to use this for FastSpring's API, because for some freaky reason they only accept x-www-form-urlencoded data in 2020. Spent all day on this because this is the first time in almost a decade an API didn't just accept JSON :(

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-02-07 11:39

    ES6 version that allows to convert nested objects and arrays just use like encodeURI(getUrlString({a: 1, b: [true, 12.3, "string"]})).

    getUrlString (params, keys = [], isArray = false) {
      const p = Object.keys(params).map(key => {
        let val = params[key]
    
        if ("[object Object]" === Object.prototype.toString.call(val) || Array.isArray(val)) {
          if (Array.isArray(params)) {
            keys.push("")
          } else {
            keys.push(key)
          }
          return getUrlString(val, keys, Array.isArray(val))
        } else {
          let tKey = key
    
          if (keys.length > 0) {
            const tKeys = isArray ? keys : [...keys, key]
            tKey = tKeys.reduce((str, k) => { return "" === str ? k : `${str}[${k}]` }, "")
          }
          if (isArray) {
            return `${ tKey }[]=${ val }`
          } else {
            return `${ tKey }=${ val }`
          }
    
        }
      }).join('&')
    
      keys.pop()
      return p
    }
    
    0 讨论(0)
  • 2021-02-07 11:41
    export function param( params ) {
        const p = new URLSearchParams;
        for( const [ key, value ] of Object.entries( params ) ) {
            p.set( key, String( value ) );
        }
        return p.toString();
    }
    
    0 讨论(0)
  • 2021-02-07 11:46

    @Amaynut's answer is awesome. But I do some simplify:

    const obj = {
      userid: 1,
      gender: 'male'
    }
    
    const params = Object.keys(obj).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k])).join('&')
    

    or maybe modulize it using es6 module:

    util.js

    export default {
      params (obj) {
        return Object.keys(obj).map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k])).join('&')
      }
    }
    

    and use like this:

    import util from './util'
    
    const q = {
      userid: 1,
      gender: 'male'
    }
    
    const query = util.params(q)
    
    console.log(query)
    
    0 讨论(0)
提交回复
热议问题