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

84
Visualizações
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 à 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