0

Array

var array = [
    {
        item: "abcd1234",
        data: "something"
    },
    {
        item: "4321dcba",
        data: "something"
    },
];

Array length can be randomly from 1 to 10

I'm making http request for all these items.

array.forEach(function(item) {

    var url = "www.something.com?id=" + item.item;

    //making request

});

Now I need 1 - 10 requests per array depends on a array length.

Lets say I have 10 arrays with 10 elements in it. Its 100 requests.

I could do this with only 1 request per array if I use url like this

www.something.com?id=abcd1234&id2=4321dcba

How do I loop all array values to the url if I don't know how many elements there is?

3 Answers 3

2

Use array-style URL parameter names. Most server-side libraries and frameworks will collect these into an array (e.g. $_GET['id'] will be an array in PHP).

You can use .map() to return an array of all the parameters, and .join() to connect them with &.

var array = [{
    item: "abcd1234",
    data: "something"
  },
  {
    item: "4321dcba",
    data: "something"
  },
];

var url = 'www.something.com?' +
  array.map(function(item) {
    return 'id[]=' + encodeURIComponent(item.item);
  }).join('&');

console.log(url);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the reduce() method:

const array = [
  {
    item: "abcd1234",
    data: "something"
  },
  {
    item: "4321dcba",
    data: "something"
  }
];
const url = array.reduce(
  (acc, x, i) => acc + (i === 0 ? `?id=${x.item}` : `&id${i + 1}=${x.item}`),
  'www.something.com'
);
console.log(url);

If your array looks like ["abcd1234", "4321dcba"], try this:

const array = ['abcd1234', '4321dcba'];
const url = array.reduce(
  (acc, x, i) => acc + (i === 0 ? `?id=${x}` : `&id${i + 1}=${x}`),
  'www.something.com'
);
console.log(url);

1 Comment

perfect. What if I have array like this? var array = ["abcd1234", "4321dcba"];
1
var url = "www.something.com?"+items.map((item,id)=>"id"+((id||-1)+1)+"="+item.item).join("&");

You can map each item to its query parameter, and then join with the &...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.