Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda