skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search