在 React 中使用 array-like 查询参数创建 URL

Create URL with array-like query params in react

当某个组的值为真时,我希望 URL 以数组类型的方式组成,如下图所示。其中 URL 包含真值的名称和真值所属的组。

这将有助于 post 实际 groups 数据 - 而不是图像。以下可能是实现所需 URL suffix/search-terms:

的一种可能解决方案

代码段

// 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));

说明

在上面的代码片段中提供了内联描述。