Plain Javascript Equivalent of jQuery.param()

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

提交回复
热议问题