-1

I need to be able to execute await axios.post (api, data)

taking all the values of parameters

const parameters = {
  userId: [ '2', '4' ],
  categoryId: '2'
}

that is, all possible combinations: userId=2&categoryId=2 y userId=4&categoryId=2

What I have:

const data = {};

const api = url_api + "?" + "userId=" + userId + "&categoryId =" + categoryId;

const resp = await axios.post(api, data);

How can I do it?

And how would it be for the cases that parameters is:

const parameters = {
  userId: [ '2', '4' ],
  categoryId: [ '1', '6' ]
}

all possible combinations: userId=2&categoryId=1, userId=2&categoryId=6, userId=4&categoryId=1, userId=4&categoryId=6

Thanks!

bonnegnu
  • 175
  • 3
  • 12
  • 1
    Seems you just need to loop over one set of values in an outer loop while looping over the other in an inner loop, and form the requests. What have you tried already? Please update your question to include a [Minimal, Complete, and Reproducible Code Example](https://stackoverflow.com/help/minimal-reproducible-example). – Drew Reese Jul 23 '21 at 05:19
  • @DrewReese thanks for your answer. That is precisely what I try to learn to do: It would be something like this https://stackoverflow.com/questions/36413159/understanding-nested-for-loops-in-javascript/51902299 – bonnegnu Jul 23 '21 at 05:33

1 Answers1

1

I think you should use inner & outer loop for it.

if your data is like this, do below.

const parameters = {
  userId: [ '2', '4' ],
  categoryId: [ '1', '6' ]
};

const dataList = [];

parameters.userId.forEach(u => {
  parameters.categoryId.forEach(c => {
    dataList.push(`${url_api}?userId=${u}&categoryId=${c}`);
  })
});

dataList.forEach(async(d) => {
  const res = await axios.post(d, data);
...
});

and if your data can be like this, do below.

const parameters = {
  userId: [ '2', '4' ],
  categoryId: '3',
};

const dataList = [];

parameters.userId.forEach((u) => {
  parameters.categoryId.length <= 1
    ? dataList.push(`${url_api}?userId=${u}&categoryId=${parameters.categoryId}`)
    : parameters.categoryId.forEach((c) => {
        dataList.push(`${url_api}?userId=${u}&categoryId=${c}`);
      });
});

dataList.forEach(async(d) => {
  const res = await axios.post(d, data);
...
});