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

167
Visualizações
Object index inside for loop in JavaScript

I have the following problem using javascript (using node.js and mongoose): I have 2 objects, the first object_1 = {"title": "Equipment 1", "description": "My equipment 1"} and the second object_2 = {"title": "Equipment 2", "description": "My gear 2"}. The problem I'm having is that I'm trying to overwrite my second object with the information from the first, and I'm using the following code for this:

for (let i in object_1) {
    object_2.i = object_1.i;
}

And the problem I see happening, is that the index variable "i" inside the loop is not being "attached" when I search for object_2.i and object_1.i.

I tested it outside the loop and my code works very well, I would like to know how I use this 'for' loop index in this case?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The i inside the loop returns "object_index" as a string. What you're doing in this code is object_2."title" = object_1."title" which will fail because you can't access the key inside an object like this. You have to use it like object_1[i] = object_2[i] and it should work. One other way of handling this is object_1 = {...object_1, ...object_2} without having to do a for loop.

about 4 years ago · Juan Pablo Isaza Relatório

0

The other answer is the real answer, but I also wanted to point out that another way to attain your desired functionality is to use Object.assign, which is supported by more browsers as compared to the spread operator (...):

Object.assign(object_1, object_2);
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