Call a function multiple times and return an array of objects

Asked

Viewed 176 times

-1

I am using an API that returns an array of objects according to the month. If I run the function at the current date, for example, it returns me:

[{Id: 1, Title: 'X'}, {Id: 2, Title: 'Y'}]

The problem is that the API only returns me for the month the user chooses, and I wanted to call this function several times to pick up biannual/annual. My idea:

[...Array(NÚMERO DE MESES QUE O USUÁRIO DIGITAR)].forEach((_, i) => this.getItems(i + 1))

My question is how to put all this data in just one array, if it returns me an array in each of the cases?

1 answer

1

First, if you want to iterate through the amount of months the user types, you don’t have to make this whole complication of [...Array(etc)].forEach(etc). Just make a for simple, starting from index 1 (since you pass i + 1 for the function, then do the loop with the correct values, because then you do not need to add 1, and it is even easier to understand and maintain, in my opinion).

Finally, you can use the method concat to concatenate the arrays returned to each call:

let meses = // quantidade de meses que o usuário digitar
let resultado = [];
for (let i = 1; i <= meses; i++) {
    resultado = resultado.concat(this.getItems(i));
}

It is worth noting that concat does not modify the original array. Instead, it returns a new array with the result of the concatenation, so I need to assign the return to a variable - in this case, I’m using the same, so at the end of the loop, resultados will have all the results of getItems concatenated into a single array.

Example:

function getItems(i) { // retorna um array qualquer
    return [ {Id: i, Title: 'X' + i}, {Id: i + 1, Title: 'Y' + i} ];
}

// número de meses
let meses = 4;
let resultado = [];
for (let i = 1; i <= meses; i++) {
    resultado = resultado.concat(getItems(i));
}
console.log(resultado);


Another alternative is to use push, passing the return of getItems using the syntax of spread (the 3 points ..., which expands the returned array, causing each element of it to be passed as an argument to push, what causes them to be added in the array resultado):

let resultado = [];
for (let i = 1; i <= meses; i++) {
    resultado.push(...this.getItems(i));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.