Flatten a javascript object to pass as querystring

前端 未结 12 1900
半阙折子戏
半阙折子戏 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: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/

提交回复
热议问题