0

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-%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 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.

m9m9m
  • 1,655
  • 3
  • 21
  • 41
  • 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 Oct 11 '18 at 11:15
  • [This](https://www.npmjs.com/package/build-url) looks promising. You can pass the object as you described into this and it will be appended as url query params – parohy Oct 11 '18 at 11:16

1 Answers1

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));
Dan
  • 8,041
  • 8
  • 41
  • 72