0

I tried converting an object into a querystring, but I don't understand how to convert a nested object and an array.

const queryObj = {
  page: 1,
  title: 'myTitle',
  startDate: '2222-01-01',
  endDate: '2022-02-05',
  id: 'jsgfdasjgfui2323gsdaa34g345',
  additional: [
    {
      placeNumber: 1,
      productNumber: 3,
      productSpec: [3, 12, 6],
    },
  ],
  price: {
    min: 1,
    max: 10000,
  },
};

I tried it this way:

const fn = (queryObj, query = '') => {
  for (const [key, value] of Object.entries(queryObj)) {
    query += `${key}=${value}&`
  }
  return encodeURI(query);
}

The result I got:

page=1&title=myTitle&startDate=2222-01-01&endDate=2022-02-05&id=jsgfdasjgfui2323gsdaa34g345&additional=%5Bobject%20Object%5D&price=%5Bobject%20Object%5D&

Do I need to use recursion to somehow convert the nested object and array? (I don't know how to do this yet, can anyone show me?)

The result I need:

page=1&title=myTitle&startDate=2222-01-01&endDate=2022-02-05&id=jsgfdasjgfui2323gsdaa34g345&additional=%5B%7B"placeNumber"%3A1%2C"productNumber"%3A0%2C"productSpec"%3A%5B%5D%7D%5D&price=%7B"min"%3A1%2C"max"%3A10000%7D
Lex2000
  • 155
  • 1
  • 1
  • 12

0 Answers0