Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 219
Dax Avatar asked Feb 27 '19 19:02

Dax


People also ask

How is a query string generated?

Query strings are also generated by sending a form or by a user typing a query into the address box of the browser. Query strings are contained in request headers. It is wise to not trust the data that is contained in headers, as this information can be falsified by malicious users.

How do you parse a Querystring?

The ParseQueryString method uses UTF8 format to parse the query string In the returned NameValueCollection, URL-encoded characters are decoded and multiple occurrences of the same query string parameter are listed as a single entry with a comma separating each value.

What is query string with example?

A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a page, or jumping to positions in multimedia content.

What is in a query string?

A query string is a set of characters tacked onto the end of a URL. The query string begins after the question mark (?) and can include one or more parameters. Each parameter is represented by a unique key-value pair or a set of two linked data items. An equals sign (=) separates each key and value.


1 Answers

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

like image 98
Maciej Kozieja Avatar answered Sep 18 '22 12:09

Maciej Kozieja