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
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);
const activeFilters = {category: {'1': 'View All','2': ' Flats'},brand: {'1': 'Fits'}}
const queryParams = Object.entries(activeFilters).map((query) => {
//Join all query keys values with ','
const values = Object.keys(query[1]).map((val) => val).join(',');
//add these values to name of the query
return query[0]+'='+values;
}).join('&'); //join final result with '&'
console.log(queryParams)
url = 'https://google.com?'+queryParams;
console.log(url)
I will use qs package to stringify the data to URL query parameters. But first, we need to convert the data like below:
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' })
// 'a=b,c'
The encoding can be disabled by setting the encode option to false.
E.g.
var qs = require("qs")
const activeFilters = {
category: {
'1': 'View All',
'2': ' Flats'
},
brand: {
'1': 'Fits'
}
}
const r = Object.keys(activeFilters).reduce((acc, cur) => {
acc[cur] = Object.keys(activeFilters[cur]);
return acc;
}, {})
const search = qs.stringify(r, {arrayFormat: 'comma', encode: false})
console.log(search)
// "category=1,2&brand=1"
console.log(`https://api.websiteurl.com/products?${search}`)
// "https://api.websiteurl.com/products?category=1,2&brand=1"