'Create URL with array-like query params in react

When a value from a certain group is truthy, I want the URL to be composed in an array type way like in the pictures below. Where the URL contains the name of the truthy value and the group in which the truthy value belongs to.

enter image description here

enter image description here

enter image description here



Solution 1:[1]

It will be helpful to post the actual groups data - rather than images. The below may be one possible solution to achieve the desired URL suffix/search-terms:

Code Snippet

// helper method to get each search-term in required format
const getPartialUrl = (obj, name) => (
  Object.entries(obj)
  .filter(([k, v]) => (!!v))
  .map(([k, v], i) => `search[${name}][${i}]=${k}`)
  ?.join('&')
);

// use the helper method for 'status' and 'categories'
const getUrl = obj => {
  const staSfx = getPartialUrl(obj?.sta, 'status');
  const catSfx = getPartialUrl(obj?.cat, 'categories');
  if (catSfx.length > 0) {
    if (staSfx.length > 0) return `test.io/assets?${catSfx}&${staSfx}`;
    return `test.io/assets?${catSfx}`;
  } else {
    if (staSfx.length > 0) return `test.io/assets?${staSfx}`;
    return 'test.io/assets';
  }
};

// raw data
const gr = {
 sta: {
  "bn": false,
  "oa": false,
  "nw": false,
  "ho": false
 },
 cat: {
  "ar": false,
  "co": false,
  "mu": false,
  "sp": false
 }
};

// call the method using appropriately set-up data
console.log(
  'bn: true, rest all false:\nurl: ',
  getUrl({...gr, sta: {...gr.sta, bn: true}})
);
console.log(
  'bn: true, oa: true, rest all false:\nurl: ',
  getUrl({...gr, sta: {...gr.sta, bn: true, oa: true}})
);
console.log(
  'bn: true, oa: true, ar: true, rest all false:\nurl: ',
  getUrl({...gr, sta: {...gr.sta, bn: true, oa: true}, cat: {...gr.cat, ar: true}})
);

console.log('all false\nurl: ', getUrl(gr));

Explanation

Descriptions are provided inline in the above code snippet.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jsN00b