Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.

    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.

    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.

    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.

    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.

    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.

    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.