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

Time:05-23

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]
            }
        }
} 

CodePudding user response:

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;

CodePudding user response:

You can use the map method to achieve what you want

return PackInput.map((element) => ({
  TimestampUTC: Date.now(),
  Payload: {
    ItemID : element
  }
 })
)

A return statement ends the execution of a function, and returns control to the calling function/upper scope.

  • Related