I have an object and I need to pass it to the ajax request.
JavaScript
x
18
18
1
advanceSearch(e, field) {
2
3
this.searchString.push({
4
[field] : e
5
});
6
7
let q = new URLSearchParams(this.searchString).toString();
8
9
// this.searchTerm = e;
10
http.get('projects/search/'+q)
11
.then( ( response ) => {
12
console.log( response )
13
})
14
.catch( ( error ) => {
15
16
});
17
},
18
Here thissearchString
is an array of object. I need to pass this array of object to the URL. So, I am using URLSearchParams
but got this error message:
JavaScript
1
2
1
TypeError: Failed to construct 'URLSearchParams': The object must have a callable @@iterator property
2
Advertisement
Answer
I think you not understand the function of URLSearchParams. Here, what this function do:
JavaScript
1
4
1
const paramsString = "myquery=value&topic=api"
2
const searchParams= new URLSearchParams(this.searchString)
3
// Convert the string into a URLSearchParams, this allow multiples methods on it.
4
With that you can apply multiple function, the common is to use it like that:
JavaScript
1
9
1
// const searchParams= new URLSearchParams(this.searchString)
2
for (let p of searchParams) {
3
console.log(p);
4
}
5
6
Output:
7
- ['myquery', 'value']
8
- ['topic', 'api']
9
Relative to https://developer.mozilla.org/fr/docs/Web/API/URLSearchParams
If i see your code, you want exactly the opposite of that.
You can easly do that like that:
JavaScript
1
13
13
1
const paramsString = {
2
myquery: 'value',
3
topic: 'api'
4
}
5
6
Object.entries(paramsString).map(params => `${params[0]}:${params[1]}`).join('&')
7
// Object entries define a value and a key. You map on that and got params[0] wich is a key and params[1] the value.
8
// In map you return a string and receive a array with ['key:value']
9
// You join all array to convert in a string and set a & between
10
11
output:
12
- 'myquery:value&topic:api'
13
With a array of object:
JavaScript
1
13
13
1
const paramsString = [{ id : 1 }, { brand : 'bata' }, { price : 123} ]
2
3
const result = paramsString
4
.map((params) =>
5
Object.entries(params).map(
6
(keyValue) => `${keyValue[0]}:${keyValue[1]}`
7
)
8
)
9
.join('&')
10
// You got each object on map
11
// Convert him to key & value like before and return a array with string
12
// Join each array with '&'
13