javascriptreactjsurlquery-string

How to generate query string from a nested object


I want to generate a query string for my advanced filter. My object looks as follows:

{
   searchValue: {
     firstName: "John",
     lastName: "Doe",
     postalCode: "3130",
     city: "New York"
   },
    page: 1
 }

I'm using the querystring library to try and format my desired string.

export function updateAdvancedSearchQueryString<T>(props: RouteComponentProps, newValues: T) {
  props.history.push({
    pathname: props.location.pathname,
    search: queryString.stringify(newValues)
  });
}

The output I want to achieve:

/trainers?page=1&searchValue=firstName=John&lastName=Doe&postalCode=3130&city=New_York

The output I'm currently getting with this:

/trainers?page=1&searchValue=%5Bobject%20Object%5D

How can I generate my desired querystring from the nested object?


Solution

  • You can have many levels of nesting so you should do it recursively.

    Something like this shoud be fine

    const data = {
      searchValue: {
        firstName: "John",
        middleInitial: null,
        lastName: "Doe",
        postalCode: "3130",
        city: "New York"
      },
      page: 1
    }
    
    const createQueryString = (data) => {
      return Object.keys(data).map(key => {
        let val = data[key]
        if (val !== null && typeof val === 'object') val = createQueryString(val)
        return `${key}=${encodeURIComponent(`${val}`.replace(/\s/g, '_'))}`
      }).join('&')
    }
    
    console.log(createQueryString(data))

    But you have to consider cases in with you pass some object with function as one of it's value, how you will handle arrays things like that. But the basic idea is simple: if you find object as the value use the same function to turn it into querystring