Arif Nurdiansyah
Arif Nurdiansyah

Reputation: 80

Axios - Associative Array in params

I currently have an associative array

let filter = []
filter['parent_id'] = 1

my axios code

const request = await axios.get(`${api.url}`, {
            ...config,
            paramsSerializer: {
                filter                
            }
        });

but it's did not make output as what i expected.

in the url it should be url?filter['parent_id']=1

is there any idea how to do this?

Thank You

SOLVED

let filter = []
filter['parent_id'] = ''
filter['country'] = 'indonesia'
const params = {}
Object.keys(filter).map((item,index) => {
  console.log(item, index)
  const key = `filter[${item}]`
  Object.assign(params, {[key]: filter[item]})
})
console.log(params)

Upvotes: 2

Views: 1109

Answers (3)

jsamaniegog
jsamaniegog

Reputation: 26

axios.get(
    'URL', 
    {
        params: {
            param_name: multidimensional_associative_array
        },
        paramsSerializer: function (params) {
            return $.param(params)
        },
    }
);

This is my solution using jQuery, the doc shows how to do it with npm QS: https://axios-http.com/es/docs/req_config

Upvotes: 0

Arif Nurdiansyah
Arif Nurdiansyah

Reputation: 80

I solved this issues, with looping the keys of the arrays, and create the params, look below for the code

let filter = []
filter['parent_id'] = ''
filter['country'] = 'indonesia'
const params = {}
Object.keys(filter).map((item,index) => {
  console.log(item, index)
  const key = `filter[${item}]`
  Object.assign(params, {[key]: filter[item]})
})
console.log(params)

Upvotes: 1

lehm.ro
lehm.ro

Reputation: 762

So as I understood you want to send each value of the array as a parameter with a GET request. The easiest way is to create a string you can attach to the url.

//your array *side note, let will only be available in block scope not global, not sure which scope you have to use filter, just keep that in mind, ill use var just to be as general as possible. You can change this!
var filter = []
var my_get_params = "";
for(var key in filter) {
  let this_value = filter[key]
  if(my_get_params.length > 0)  {
   //we are at the beginning, we use ? instead of & to concat params
  my_get_params+= "?filter_"+key+"="+this_value;
  } else {
   //we are at the beginning, we use ? instead of & to concat params
   my_get_params+= "&filter_"+key+"="+this_value;
  }
}

Now my_get_params will look like: ?filter_0=myvalue&filter_1=myvalue2....

Let's add it to the request:

    axios.get('/your_request_url'+my_get_params)
    .then( (response) => {
        //console.log("response", response.data);
        return response.data;
    })
    .catch( (error) => {
        //console.log(error);
        return error;
    });  

Upvotes: 0

Related Questions