I am trying to create a url based on the data I get from the user.if we consider this to be my url:
let url = new URL('http://localhost:8080/api/movies/search/search');
I add the search fields like this:
for (let item in data) {
url.searchParams.set(item,data[item]);
}
but at the end of my url I want to add the sort type for it to look something like this:
const url = `http://localhost:8080/api/movies/search/search?title=something&minRate=10&genre=action&sort=title,asc`;
so how should I add the last part with the comma:
,asc
to the url?
CodePudding user response:
Based on comments on the question above...
If data
is this:
{
title: 'the',
minRate: 2,
genre: 'action',
sortType: 'title',
type: 'asc'
}
And the result you want is this:
http://localhost:8080/api/movies/search/search?title=the&minRate=2&genre=action&sort=title,asc
Then data
doesn't match what you're looking for. It has two properties called sortType
and type
, and you want one combined property called sort
.
Project the object into the shape you want, then use that new object to build your params:
let data = {
title: 'the',
minRate: 2,
genre: 'action',
sortType: 'title',
type: 'asc'
};
let url = new URL('http://localhost:8080/api/movies/search/search');
// create the object you want:
let urlData = {
title: data.title,
minRate: data.minRate,
genre: data.genre,
sort: `${data.sortType},${data.type}`
};
// then add params from *that* object:
for (let item in urlData) {
url.searchParams.set(item, urlData[item]);
}
console.log(url);
(Note that the ,
character is URL-encoded by default.)
Basically, don't change the logic to work around the data structure. Keep the logic simple and change the data structure to what you need it to be.