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

136
Visualizações
Iteratively saving to an object using bracket notation having no effect on object

I am passing a mongo cursor called resources to this function. I want to restructure the resources by creating an empty object and using bracket notation to save the resources to the object. But it doesn't take -- I simplified my code as much as I could to demonstrate how it is behaving completely differently than I would expect.

I don't know why Mongo would be involved here because typeof r.id === string, but I did want to mention that. Especially because, when I iterate through a different data structure with .forEach, this is not a problem.

I am using Typescript.

const restructured_resources = async(resources: any, db: any) => {
    

    let restructured_resources: any = {}
    resources.forEach((r: any) => {
        const id = r.id
        restructured_resources[id] = "yo"
    })

    console.log(restructured_resources) //{}

})

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

0

Added the await keyword in front of the forEach function results in the object becoming populated with the desired key value pairs. This leads me to believe that iterating through a Mongo cursor with a forEach loop is not a normal synchronous task, and is queued after the console.log statement.

const restructured_resources = async(resources: any, db: any) => {

    const thing: any = {}
    await resources.forEach((resource: any) => {
        restructured_resources[resource.id] = "yo"
    })

    console.log(restructured_resources)
about 4 years ago · Juan Pablo Isaza Relatório

0

This should work, so if it isn't, it's probably an async problem.

const restructured_resources = (resources) => {
  let restructured_resources = {}
  resources.forEach((r) => {
    const id = r.id
    restructured_resources[id] = "yo"
  })

  console.log(restructured_resources) //{}

}

restructured_resources([{id: 1},{id: 2},{id: 3},{id: 4},{id: 15},]);

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