0

I need to send type related params in sparse fieldset way, please provide a way to construct below url.

const page = {
  limit: 0,
  offset:10,
  type: {
     name: 's',
     age:'n'
   }
}

i tried to convert above object with urlsearch params but still not getting like below url.

https://sample.run/api/product?limit=0&offset=10&type[name]=s&type[age]=n
InSync
  • 4,851
  • 4
  • 8
  • 30
skyshine
  • 2,767
  • 7
  • 44
  • 84

2 Answers2

0

You can use this code, the formatting is bit bad, but I hope your linter fixes it :)

const createQuery = (obj, nestedObjKey) => {
  const query = Object.keys(obj)
    .reduce((acc, key) => 
      `${acc.length ? acc + '&' : ''}${typeof obj[key] === 'object' ? createQuery(obj[key], key) : nestedObjKey ? nestedObjKey + '[' + key + ']=' + obj[key] : key + '=' + obj[key]}`,
      ''
    )
  return query
}

Maybe this answer is more appropriate for you if you have multiple nested fields: Want to convert a nested object to query parameter for attaching to url

Alopwer
  • 611
  • 8
  • 22
0

const page = {
  limit: 0,
  offset:10,
  type: {
     name: 's',
     age:'n'
   }
}

function parseParams(o, parent){
  let params = [];
  for(const k in o){
    const value = o[k];
    if(typeof value === 'object'){
      params = params.concat(parseParams(value, k));
    } else {
      let key = (typeof parent !== 'undefined') ? `${parent}[${k}]` : k;
      params.push(`${key}=${encodeURIComponent(value)}`);
    }
  }
  return params;
}

let url = 'https://sample.run/api/product?' + parseParams(page).join('&');
console.log(url);
Tom
  • 151
  • 6