Skip to content
Advertisement

Vue JS – Using URLSearchParams is showing me error

I have an object and I need to pass it to the ajax request.

advanceSearch(e, field) { 
           
    this.searchString.push({
        [field] : e
    });

    let q = new URLSearchParams(this.searchString).toString();
    
    // this.searchTerm = e;
    http.get('projects/search/'+q)
    .then( ( response ) => {
        console.log( response )
    })
    .catch( ( error ) => {

    });
},

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:

TypeError: Failed to construct 'URLSearchParams': The object must have a callable @@iterator property

Advertisement

Answer

I think you not understand the function of URLSearchParams. Here, what this function do:

const paramsString = "myquery=value&topic=api"
const searchParams= new URLSearchParams(this.searchString) 
// Convert the string into a URLSearchParams, this allow multiples methods on it.

With that you can apply multiple function, the common is to use it like that:

// const searchParams= new URLSearchParams(this.searchString) 
for (let p of searchParams) {
  console.log(p);
}

Output:
- ['myquery', 'value']
- ['topic', 'api']

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:

const paramsString = {
 myquery: 'value',
 topic: 'api'
}

Object.entries(paramsString).map(params => `${params[0]}:${params[1]}`).join('&')
// 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.
// In map you return a string and receive a array with ['key:value']
// You join all array to convert in a string and set a & between

output:
- 'myquery:value&topic:api'

With a array of object:

const paramsString =  [{ id : 1 }, { brand : 'bata' }, { price : 123} ]

const result = paramsString
    .map((params) =>
        Object.entries(params).map(
            (keyValue) => `${keyValue[0]}:${keyValue[1]}`
        )
    )
    .join('&')
// You got each object on map
// Convert him to key & value like before and return a array with string
// Join each array with '&'
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement