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

83
Vistas
Appending object to array from a callback within a for loop

I am trying to push an object to an array, from within a for loop. The array appears empty in the end. When I console.log() the data I am attempting to push, it appears to be correct. The purpose of this code is to read JSON from a file, use the data from this to create an object and add this object to an array. The reason I am using an array and loop, is so that I can repeat this process for multiple files. Then I will save the final array with all the objects to a single file.

I am doing this in Node.JS

This is my code so far:

const fs = require('fs')

const create_data = async (number) => {
    let finished_data = []
    for(let i = 1; i <= number; i++){
        const path = "./generated_images/" + i + "/output.json"
        fs.readFile(path, 'utf8', function readFileCallback(err, data){
            if (err){
                console.log(err);
            } else {
                let obj = JSON.parse(data);
                finished_data.push({
                    id: obj.id,
                    img_url: obj.public_url,
                })
            }
        });
    }
    return finished_data
}

create_data(5).then(res => {
    console.log(res)
}) // I am just logging the data, eventually I will put an fs.writeFile() here, to write the array of objects to a file.
about 4 years ago · Juan Pablo Isaza
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