在不知道JavaScript对象的键的情况下,我如何将…
var obj = {
param1: 'something',
param2: 'somethingelse',
param3: 'another'
}
obj[param4] = 'yetanother';
…到…
var str = 'param1=something¶m2=somethingelse¶m3=another¶m4=yetanother';
...?
在不知道JavaScript对象的键的情况下,我如何将…
var obj = {
param1: 'something',
param2: 'somethingelse',
param3: 'another'
}
obj[param4] = 'yetanother';
…到…
var str = 'param1=something¶m2=somethingelse¶m3=another¶m4=yetanother';
...?
当前回答
如果你使用的是NodeJS 13.1或更高版本,你可以使用本地querystring模块来解析查询字符串。
const qs = require('querystring');
let str = qs.stringify(obj)
其他回答
Object.toparams = function ObjecttoParams(obj)
{
var p = [];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
如果你需要一个递归函数来根据给定的对象生成正确的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"
使用Axios和无限深度:
<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>
祝你好运…
Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')
试试这个…这也适用于嵌套对象。
let my_obj = {'single':'this is single', 'nested':['child1','child2']};
((o)=>{ return Object.keys(o).map(function(key){ let ret=[]; if(Array.isArray(o[key])){ o[key].forEach((item)=>{ ret.push(`${key}[]=${encodeURIComponent(item)}`); }); }else{ ret.push(`${key}=${encodeURIComponent(o[key])}`); } return ret.join("&"); }).join("&"); })(my_obj);