Plain Javascript Equivalent of jQuery.param()

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

提交回复
热议问题