I have an object similar to below
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'
};
I want this object to be turned to like below https://www.example.com/properties.php?token=78fe6df3f&id=12345&price=0ドル%20-%203,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
How can I get this in react native. In javascript $.param(obj) does this job. Please guide me.
I want the above to do fetch calls in react native. The object will be generated by the filter form.
asked Oct 11, 2018 at 11:11
m9m9m
1,7215 gold badges24 silver badges48 bronze badges
-
I am sure if you google for js url builder library you can find a lot of 3rd party dependencies which process object into query params.parohy– parohy2018年10月11日 11:15:23 +00:00Commented Oct 11, 2018 at 11:15
-
This looks promising. You can pass the object as you described into this and it will be appended as url query paramsparohy– parohy2018年10月11日 11:16:55 +00:00Commented Oct 11, 2018 at 11:16
1 Answer 1
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));
answered Oct 11, 2018 at 11:22
Dan
8,9229 gold badges46 silver badges82 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
parohy
This is nice but an explanation should be nice.