'How would I be able to return more than one object based on user input amount

Let's say PackInput is an array input.

What I'd like to do's return a dynamic amount of objects depending on how large the input array PackInput is.

For example: if PackInput is [4,5,6], then I'd like three objects returned for each ItemID.

For example: return {... ItemID: 4 ...}, return {... ItemID: 5 ...}, return {... ItemID: 6 ...}.

My current code below is only grabbing the first item of the array instead of all of them and I'm not sure why. I've turned my wheels on this for so long and now I've hit a wall. What am I doing wrong?

for(let i = 0; i < PackInput.length; i++) {      
        return {
            TimestampUTC: Date.now(),
            Payload: {
                ItemID : PackInput[i]
            }
        }
} 

Updated:

let array = PackInput.map((items) => ({
        TimestampUTC: Date.now(),
        Payload: {
            ItemID : items
        }
   })
);

let objects = array.reduce(function(target, key, index) {
    target[index] = key;
    return target;
}) 

return objects;


Solution 1:[1]

You can return an array/object. The problem is that you can call return only once in a function and as soon as a function reaches return it would be returned to the caller scope. You can use the loop to create the array/object and then return the final value:

let array = [];
for(let i = 0; i < PackInput.length; i++) {      
        array.push({
            TimestampUTC: Date.now(),
            Payload: {
                ItemID : PackInput[i]
            }
        });
} 

return array;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amir MB