1. 16
    Create a Query String from an Object using Ramda's toPairs function
    2m 24s
⚠️ This lesson is retired and might contain outdated information.

Create a Query String from an Object using Ramda's toPairs function

Andy Van Slaars
InstructorAndy Van Slaars

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 10 months ago

In this lesson, we'll use Ramda's toPairs function, along with map, join, concat and compose to create a reusable function that will convert an object to a querystring.

[00:00] I've included Ramda, and I'm using de-structuring to grab a few of its utility functions. I also have a query string object with the page size and total property. My expected result is a query string made up of those key/value pairs. I'd like to replace this hard-coded value with a function that'll take in our object and result in this string.

[00:19] I'm going to grab the string, and I'm going to cut it. I'm just going to drop it up here in a comment so we have it for reference. I'm going to start by setting my result to create qs, which is going to be a function that we'll create in a second. I'm going to pass that our query-string object. Then I'll define our create qs function.

[00:40] For now I'm going to set that to equal two pairs. We'll see that it's generated an array of arrays where each inner array is a key/value pair. We're going to need to process this further, so I'm going to make this a composition. I'm going to wrap. I might call it two pairs in a compose.

[01:05] After we've converted it to these nested arrays, I need to map over each one of those inner arrays and convert each of those into a string. For that I'm going to use map. Then in the map I'm going to use join, and I'm going to join each item and each inner array with an equal sign.

[01:22] We'll see our result is an array of three strings with our key and value pairs. Now that our array's been flattened out I can join each one of the strings in this array with an ampersand. We have a string that has our key/value pairs.

[01:40] The only thing left is to add the question mark to the beginning. For that I'm going to use CONCAT, and I'm just going to CONCAT with a question mark. I'm just going to newline each of these functions so it's easier to see the entire composition. You'll see that we have a function that'll take in any object and convert it into a query string.

[02:02] I can come up here if I wanted to change these values. Say I have a total of 205. We'll see there are string updates to reflect that. If I add another property, so we'll add something else, we'll see that our query string is updated to reflect that new value.