Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

Update on object:

const object = PackInput.reduce(function(previousValue, currentValue, index) {
    return {
      ...previousValue,
      [index]: currentValue
    }
}, {})

You need to provide an empty object as 2nd argument for the reduce function.

about 4 years ago · Juan Pablo Isaza Report

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!