我有一个与下面类似的对象
const params = {
token: '78fe6df3f',
id: '12345',
price: 0 - '9,000,000',
'area[]': 'Applehead Island',
'waterfront_type[]': 'Open Water',
property_type_single: 'Single Family/Site Built',
bedrooms: '0 - 5',
baths: '0 - 5',
sqft: '0 - 7500'
};
我希望将此对象变成https://www.example.com/properties.php?token=78fe6df3f&id=12345&price=$0%20-%20$3,480,000&area[]=Applehead%20Island&waterfront_type[]=Open%20Water&property_type_single=Single%20Family/Site%20Built&bedrooms=0%20-%205&baths=0%20-%205&sqft=0%20-%207500
下面的样子
我怎样才能在本机反应。在javascript $.param(obj)
中可以完成这项工作。请引导我。
我希望以上内容在react native中进行调用。该对象将由过滤器表单生成。
答案 0 :(得分:2)
const paramsToString = params => Object.entries(params).reduce((acc, [key, value], index, array) => `${acc}${key}=${encodeURIComponent(value)}${index !== (array.length - 1) ? '&' : ''}`, "");
const params = {
token: '78fe6df3f',
id: '12345',
price: '0 - 9,000,000',
'area[]': 'Applehead Island',
'waterfront_type[]': 'Open Water',
property_type_single: 'Single Family/Site Built',
bedrooms: '0 - 5',
baths: '0 - 5',
sqft: '0 - 7500'
};
console.log(paramsToString(params));
答案 1 :(得分:1)
function buildUrl(url, parameters){
var qs = "";
for(var key in parameters) {
var value = parameters[key];
qs += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&";
}
if (qs.length > 0){
qs = qs.substring(0, qs.length-1); //chop off last "&"
url = url + "?" + qs;
}
return url;
}
// example:
var url = "https://www.example.com/properties.php?";
const params = {
token: '78fe6df3f',
id: '12345',
price: 0 - '9,000,000',
'area[]': 'Applehead Island',
'waterfront_type[]': 'Open Water',
property_type_single: 'Single Family/Site Built',
bedrooms: '0 - 5',
baths: '0 - 5',
sqft: '0 - 7500'
};
console.log(buildUrl(url, params));