Flatten a javascript object to pass as querystring

前端 未结 12 1795
半阙折子戏
半阙折子戏 2020-12-04 23:24

I have a javascript object that I need to flatten into a string so that I can pass as querystring, how would I do that? i.e:

{ cost: 12345, insertBy: \'testUse

相关标签:
12条回答
  • 2020-12-05 00:02

    Here's a non-jQuery version:

    function toQueryString(obj) {
        var parts = [];
        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
            }
        }
        return parts.join("&");
    }
    
    0 讨论(0)
  • 2020-12-05 00:06

    Here is another non-jQuery version that utilizes lodash or underscore if you're already using one of those libraries:

    var toQueryString = function(obj) {
      return _.map(obj,function(v,k){
        return encodeURIComponent(k) + '=' + encodeURIComponent(v);
      }).join('&');
    };
    

    ^ I wrote that 5 years ago. An updated and more succinct version of this would now (Oct 2019) be:

    var input = { cost: 12345, insertBy: 'testUser' };
    Object.entries(input)
      .map(([k,v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
      .join('&');
    // cost=12345&insertBy=testUser
    

    Check that the runtime that you're targeting supports Object.entries() or that you're using a transpiler like Babel or TypeScript if it doesn't.

    0 讨论(0)
  • 2020-12-05 00:06

    Another version:

    function toQueryString(obj) {
        return Object.keys(obj).map(k => {
          return encodeURIComponent(k) + "=" + encodeURIComponent(obj[k])
        })
        .join("&");
    }
    
    0 讨论(0)
  • 2020-12-05 00:07

    you can use this

    function serialize(obj)
    {
        let str = []
    
        for(var p in obj)
        {
          if(obj.hasOwnProperty(p)) str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
        }
    
        return str.join('&')
    }
    

    try on JSFiddle on this link https://jsfiddle.net/yussan/kwmnkca6/

    0 讨论(0)
  • 2020-12-05 00:08

    You want jQuery.param:

    var str = $.param({ cost: 12345, insertBy: 'testUser' });
    // "cost=12345&insertBy=testUser"
    

    Note that this is the function used internally by jQuery to serialize objects passed as the data argument.

    0 讨论(0)
  • 2020-12-05 00:10

    Using Lodash library it can be done as:

    let data = {}
    
    _.map(data, (value, key) => `${key}=${value}`)
    .join("&");
    

    Note that this library has been imported as:

    window._ = require('lodash');
    
    0 讨论(0)
提交回复
热议问题