Plain Javascript Equivalent of jQuery.param()

為{幸葍}努か 提交于 2019-12-03 06:08:33

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/

ES6 gives us some nice primitives:

    // Function that parses an object of string key/value params to build up
    // a string of url params
    // requires an object with no nested values
    export function parseUrlParams(urlParams) {
        const joinByEquals = (pair) => pair.join('=')
        const params = Object.entries(urlParams).map(joinByEquals).join('&')
        if (params) {
            return `?${params}`
        } else {
        return ''
        }
    }

See it in action here: https://www.webpackbin.com/bins/-KnpOI6hb1AzTDpN3wS7

export function param( params ) {
    const p = new URLSearchParams;
    for( const [ key, value ] of Object.entries( params ) ) {
        p.set( key, String( value ) );
    }
    return p.toString();
}

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
}

@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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!