如何将对象序列化为URL查询参数列表?

2020/11/02 08:44 · javascript ·  · 0评论

在不了解JavaScript键的情况下Object,我该如何打开类似...

var obj = {
   param1: 'something',
   param2: 'somethingelse',
   param3: 'another'
}

obj[param4] = 'yetanother';

...进入...

var str = 'param1=something&param2=somethingelse&param3=another&param4=yetanother';

...?

var str = "";
for (var key in obj) {
    if (str != "") {
        str += "&";
    }
    str += key + "=" + encodeURIComponent(obj[key]);
}

示例:http//jsfiddle.net/WFPen/

如果您使用jQuery,这就是它用于参数化GET XHR请求的选项的方式:

$.param( obj )

http://api.jquery.com/jQuery.param/

一个优雅的例子:(假设您正在运行现代的浏览器或节点)

var str = Object.keys(obj).map(function(key) {
  return key + '=' + obj[key];
}).join('&');

和ES2017等效:(感谢Lukas)

let str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');

注意:encodeURIComponent()如果键/值未经URL编码,则可能要使用

一行没有依赖性:

new URLSearchParams(obj).toString();
// OUT: param1=something&param2=somethingelse&param3=another&param4=yetanother

将其与内置的URL一起使用,如下所示:

let obj = { param1: 'something', param2: 'somethingelse', param3: 'another' }
obj['param4'] = 'yetanother';
const url = new URL(`your_url.com`);
url.search = new URLSearchParams(obj);
const response = await fetch(url);

[2020年4月4日编辑]:null值将解释为字符串'null'

ES2017方法

Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&')

ES6:

function params(data) {
  return Object.keys(data).map(key => `${key}=${encodeURIComponent(data[key])}`).join('&');
}

console.log(params({foo: 'bar'}));
console.log(params({foo: 'bar', baz: 'qux$'}));

深入一层...

var serialiseObject = function(obj) {
    var pairs = [];
    for (var prop in obj) {
        if (!obj.hasOwnProperty(prop)) {
            continue;
        }
        pairs.push(prop + '=' + obj[prop]);
    }
    return pairs.join('&');
}

jsFiddle

有人在谈论对任意深对象的递归函数。

var serialiseObject = function(obj) {
    var pairs = [];
    for (var prop in obj) {
        if (!obj.hasOwnProperty(prop)) {
            continue;
        }
        if (Object.prototype.toString.call(obj[prop]) == '[object Object]') {
            pairs.push(serialiseObject(obj[prop]));
            continue;
        }
        pairs.push(prop + '=' + obj[prop]);
    }
    return pairs.join('&');
}

jsFiddle

当然,这意味着在序列化过程中会丢失嵌套上下文。

如果这些值不是以URL编码开头的,而您打算在URL中使用它们,请查看JavaScript的encodeURIComponent()

Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')

由于我对递归函数做了很多事情,因此这是我自己的版本。

function objectParametize(obj, delimeter, q) {
    var str = new Array();
    if (!delimeter) delimeter = '&';
    for (var key in obj) {
        switch (typeof obj[key]) {
            case 'string':
            case 'number':
                str[str.length] = key + '=' + obj[key];
            break;
            case 'object':
                str[str.length] = objectParametize(obj[key], delimeter);
        }
    }
    return (q === true ? '?' : '') + str.join(delimeter);
}

http://jsfiddle.net/userdude/Kk3Lz/2/

仅作记录,如果您有支持ES6的浏览器,以下是一个解决方案reduce

Object.keys(obj).reduce((prev, key, i) => (
  `${prev}${i!==0?'&':''}${key}=${obj[key]}`
), '');

这是一个正在运行的代码段!

// Just for test purposes
let obj = {param1: 12, param2: "test"};

// Actual solution
let result = Object.keys(obj).reduce((prev, key, i) => (
  `${prev}${i!==0?'&':''}${key}=${obj[key]}`
), '');

// Run the snippet to show what happens!
console.log(result);

查询中包含数组时的有用代码:

var queryString = Object.keys(query).map(key => {
    if (query[key].constructor === Array) {
        var theArrSerialized = ''
        for (let singleArrIndex of query[key]) {
            theArrSerialized = theArrSerialized + key + '[]=' + singleArrIndex + '&'
        }
        return theArrSerialized
    }
    else {
        return key + '=' + query[key] + '&'
    }
}
).join('');
console.log('?' + queryString)
new URLSearchParams({hello: 'world', foo: 'bar' }).toString()

似乎可以胜任。不需要encodeURIComponent产出hello=world&foo=bar

如果您使用的是NodeJS 13.1或更高版本,则可以使用本机querystring模块来解析查询字符串。

const qs = require('querystring');
let str = qs.stringify(obj)

如果您需要一个递归函数,该函数将根据给定的对象生成正确的URL参数,请尝试使用我的Coffee-Script。

@toParams = (params) ->
    pairs = []
    do proc = (object=params, prefix=null) ->
      for own key, value of object
        if value instanceof Array
          for el, i in value
            proc(el, if prefix? then "#{prefix}[#{key}][]" else "#{key}[]")
        else if value instanceof Object
          if prefix?
            prefix += "[#{key}]"
          else
            prefix = key
          proc(value, prefix)
        else
          pairs.push(if prefix? then "#{prefix}[#{key}]=#{value}" else "#{key}=#{value}")
    pairs.join('&')

或JavaScript已编译...

toParams = function(params) {
  var pairs, proc;
  pairs = [];
  (proc = function(object, prefix) {
    var el, i, key, value, _results;
    if (object == null) object = params;
    if (prefix == null) prefix = null;
    _results = [];
    for (key in object) {
      if (!__hasProp.call(object, key)) continue;
      value = object[key];
      if (value instanceof Array) {
        _results.push((function() {
          var _len, _results2;
          _results2 = [];
          for (i = 0, _len = value.length; i < _len; i++) {
            el = value[i];
            _results2.push(proc(el, prefix != null ? "" + prefix + "[" + key + "][]" : "" + key + "[]"));
          }
          return _results2;
        })());
      } else if (value instanceof Object) {
        if (prefix != null) {
          prefix += "[" + key + "]";
        } else {
          prefix = key;
        }
        _results.push(proc(value, prefix));
      } else {
        _results.push(pairs.push(prefix != null ? "" + prefix + "[" + key + "]=" + value : "" + key + "=" + value));
      }
    }
    return _results;
  })();
  return pairs.join('&');
};

这将构造如下字符串:

toParams({a: 'one', b: 'two', c: {x: 'eight', y: ['g','h','j'], z: {asdf: 'fdsa'}}})

"a=one&b=two&c[x]=eight&c[y][0]=g&c[y][1]=h&c[y][2]=j&c[y][z][asdf]=fdsa"

您可以使用jQuery的param方法:

var obj = {
  param1: 'something',
  param2: 'somethingelse',
  param3: 'another'
}
obj['param4'] = 'yetanother';
var str = jQuery.param(obj);
alert(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var str = '';

for( var name in obj ) {
    str += (name + '=' + obj[name] + '&');
}

str = str.slice(0,-1);

试一下。

示例: http //jsfiddle.net/T2UWT/

一种功能方法。

var kvToParam = R.mapObjIndexed((val, key) => {
  return '&' + key + '=' + encodeURIComponent(val);
});

var objToParams = R.compose(
  R.replace(/^&/, '?'),
  R.join(''),
  R.values,
  kvToParam
);

var o = {
  username: 'sloughfeg9',
  password: 'traveller'
};

console.log(objToParams(o));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>
Object.toparams = function ObjecttoParams(obj) 
{
  var p = [];
  for (var key in obj) 
  {
    p.push(key + '=' + encodeURIComponent(obj[key]));
  }
  return p.join('&');
};

此方法使用递归下降到对象层次结构并生成rails样式参数,rails会将其解释为嵌入式哈希。objToParams生成一个末尾带有“&”号的查询字符串,而objToQuery删除最后一个“&”号。

 function objToQuery(obj){
  let str = objToParams(obj,'');
  return str.slice(0, str.length);
}
function   objToParams(obj, subobj){
  let str = "";

   for (let key in obj) {
     if(typeof(obj[key]) === 'object') {
       if(subobj){
         str += objToParams(obj[key], `${subobj}[${key}]`);
       } else {
         str += objToParams(obj[key], `[${key}]`);
       }

     } else {
       if(subobj){
         str += `${key}${subobj}=${obj[key]}&`;
       }else{
         str += `${key}=${obj[key]}&`;
       }
     }
   }
   return str;
 }

您可以使用npm lib查询字符串

const queryString = require('query-string');

querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// Returns 'foo=bar&baz=qux&baz=quux&corge='
const obj = { id: 1, name: 'Neel' };
let str = '';
str = Object.entries(obj).map(([key, val]) => `${key}=${val}`).join('&');
console.log(str);

Axiosinfinite depth

<pre>
    <style>
      textarea {
        width: 80%;
        margin-bottom: 20px;
      }
      label {
        font-size: 18px;
        font-weight: bold;
      }
    </style>
    <label>URI</label>
    <textarea id="uri"  rows="7"></textarea>
    <label>All Defaults (Bonus): </label>
    <textarea id="defaults" rows="20"></textarea>
</pre>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
  const instance = axios.create({
    baseUrl: 'http://my-api-server',
    url: '/user'
  })
  const uri = instance.getUri({
    params: {
      id: '1234',
      favFruits: [
        'banana',
        'apple',
        'strawberry'
      ],
      carConfig: {
        items: ['keys', 'laptop'],
        type: 'sedan',
        other: {
          music: ['on', 'off', {
            foo: 'bar'
          }]
        }
      }
    }
  })
  const defaults = JSON.stringify(instance.defaults, null, 2)
  document.getElementById('uri').value = uri
  document.getElementById('defaults').value = defaults
</script>

祝好运...

本文地址:http://javascript.askforanswer.com/ruhejiangduixiangxuliehuaweiurlchaxuncanshuliebiao.html
文章标签:
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!