Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda