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

141
Views
loop and return a number for an ID

I need to create multiple objects, and each one must have an ID.
All of them will be inside an Array.
So it will look like this:

const array = [
{
  id: 1,
  bla: "bla"
},
{
  id: 2,
  bla: "bla"
},
{
  id: 3,
  bla: "bla"
}
]

my question is, Is there a way to create a function, the will return a number that i can put inside those id's?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

function makeArrayWithId(...objects) {
    return objects.map((o, i) => ({ id: i + 1, ...o }))
}


const arr = makeArrayWithId(
    {
        bla: "bla"
    },
    {
        bla: "bla"
    },
    {
        bla: "bla"
    },
)

console.log(arr)

it will prints:

[ { id: 1, bla: 'bla' }, { id: 2, bla: 'bla' }, { id: 3, bla: 'bla' } ]

if you already have an array that each object has no id, you can pass it to this function like this:

let myArr = [
    {
        bla: 'bla'
    },
    {
        bla: 'bla'
    },
    {
        bla: 'bla'
    },
]
myArrr = makeArrayWithId(...myArr)
console.log(myArr)

it will prints:

[ { id: 1, bla: 'bla' }, { id: 2, bla: 'bla' }, { id: 3, bla: 'bla' } ]
about 4 years ago · Juan Pablo Isaza Report

0

You likely want what we call generators/iterators.

An generator/iterator is a function that has an inner state.

In js, it's created by adding an "*" next to the "function" and using "yield" keyword instead of "return" (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield).

When the generator is called, it saves the arguments it was given and returns an iterator, on which you can call .next() to get the next value (note an object with "value" attribute is returned).

function* idGenerator (startingIndex) {
    while (true){
        //the iterator will keep his inner state
        startingIndex += 1;
        yield startingIndex;
    }
}
about 4 years ago · Juan Pablo Isaza Report

0

let array = [
{
  bla: "bla"
},
{
  bla: "bla"
},
{
  bla: "bla"
}
]


array = array.map((item, index) => Object.assign({}, item, { id: index + 1 }))

Output:

[ { bla: 'bla', id: 1 },
  { bla: 'bla', id: 2 },
  { bla: 'bla', id: 3 } ]
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!