Search code examples
javascriptreactjslodash

Javascript Convert an Object to a URL


I have an object which looks something like this:

activeFilters: {
    category: {
        '1': 'View All',
        '2': ' Flats'
    },
    brand: {
        '1': 'Fits'
    }
}

I want to map through the object and use these as URL parameters. The end result will look something like this:

https://api.websiteurl.com/products?category=1,2&brand=1

I am using react and I can use lodash. Wanted help on whats the best way to achieve this


Solution

  • You can make use of Object.entries and map to achieve the desired result

    const filters = {
      activeFilters: {
        category: {
          "1": "View All",
          "2": " Flats",
        },
        brand: {
          "1": "Fits",
        },
      },
    };
    
    const queryString = Object.entries(filters.activeFilters)
      .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(Object.keys(v))}`)
      .join("&");
    
    const url = "https://api.websiteurl.com/products";
    
    // Thanks Dai for this suggestion to encode the path.
    const result = `${url}?${queryString}`;
    console.log(result);