javascript 如何将对象数组转换为 url 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26717228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert object array to url string?
提问by Eniz Gülek
I am trying to generate javascript object array to urlstring like:
我正在尝试为 urlstring 生成 javascript 对象数组,例如:
var array = [{'name': 'foo', 'value': '2'},
{'name': 'foo', 'value': '2,8'},
{'name': 'foo', 'value': '2,10,3'}
];
// url ==> foo=2&foo=2,8&foo=2,10,3
回答by Amit Joki
You can do this
你可以这样做
var url = "";
array.forEach(function(e){
url += e.name + "=" + e.value + "&";
});
url = url.trim("&");
回答by Paul Roub
To be safe, you'd want to encode the component pieces:
为安全起见,您需要对组件进行编码:
var array = [{'name': 'foo', 'value': '2'},
{'name': 'foo', 'value': '2,8'},
{'name': 'foo', 'value': '2,10,3'}
];
var parts = [];
for ( var i = 0; i < array.length; ++i )
parts.push(encodeURIComponent(array[i].name) + '=' +
encodeURIComponent(array[i].value));
var url = parts.join('&');
console.log(url);
回答by oscarvady
Try this code:
试试这个代码:
var array = [{'name': 'foo', 'value': '2'},
{'name': 'foo', 'value': '2,8'},
{'name': 'foo', 'value': '2,10,3'}
];
var output = "";
for(var i = 0; i < array.length; i++){
output = output + array[i].name+"="+array[i].value+"&"
}
output = output.substring(0, output.length-1);
alert(output)
Here the fiddle
这里的小提琴
回答by jeremy
If your array contains object with parameters 'name' and 'value', you should use:
如果您的数组包含带有参数“名称”和“值”的对象,则应使用:
$.param(array)
$.param(数组)
回答by Joe DeRose
You'll need to loop through the array, determine whether the array entry is the first or not (so that they will be separated with ampersands, and use the JSON field names.
您需要遍历数组,确定数组条目是否是第一个(以便它们用与号分隔,并使用 JSON 字段名称。
var queryString = "";
for ( var i = 0; i++; i < array.length ) {
if ( i > 0 ) {
queryString = queryString + "&";
}
queryString = queryString + array[i]["name"] + "=" + array[i]["value"];
}
回答by Andre Figueiredo
No need loops and aux vars, Array built-in methods do it.
不需要循环和辅助变量,数组内置方法就可以做到。
> array.map(p => p.name + '=' + p.value).join('&')
'foo=2&foo=2,8&foo=2,10,3'
> array.map(function(param){
return param.name + '=' + param.value
}).join('&')
'foo=2&foo=2,8&foo=2,10,3'
safe use (but not expected OP's output):
安全使用(但不是预期的 OP 输出):
> array.map(p => encodeURIComponent(p.name) + '=' + encodeURIComponent(p.value)).join('&')
'foo=2&foo=2%2C8&foo=2%2C10%2C3'